乐闻世界logo
搜索文章和话题

React -query - How can I access my queries in multiple components?

1个答案

1

In React Query, query results can be shared and synchronized across multiple components. One of React Query's design principles is to simplify and optimize data fetching, especially when using data across components.

To access query results across multiple components, you typically use the useQuery hook. useQuery fetches and caches data using a unique key, allowing any component that calls useQuery with the same key to access the same query results and state.

Here is a basic example of using useQuery:

jsx
import { useQuery } from 'react-query'; const fetchUserData = async (userId) => { const response = await fetch('/api/user/' + userId); if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }; function UserProfile({ userId }) { const { data, isLoading, error } = useQuery(['user', userId], () => fetchUserData(userId), { // You can add other options here, such as staleTime, cacheTime, etc. }); if (isLoading) return 'Loading user...'; if (error) return 'An error has occurred: ' + error.message; // render data return ( <div> <h1>{data.name}</h1> <p>Email: {data.email}</p> // ...other user information </div> ); }

If you need to use the same user data in another part of the application, you can use the same useQuery in a new component.

jsx
function UserPosts({ userId }) { const { data, isLoading, error } = useQuery(['user', userId], () => fetchUserData(userId)); // Same handling for loading and error states // render user posts return ( // ... ); }

In this example, regardless of whether UserProfile and UserPosts are on the same page or different pages, they can access the same user data through the identical query key (in this case, ['user', userId]). If these components are mounted simultaneously, the second component will immediately fetch data from the cache after the first request completes, without initiating a new request.

React Query's caching and synchronization mechanisms ensure data consistency and reduce unnecessary network requests, thereby improving application performance.

2024年6月29日 12:07 回复

你的答案