In React Query, you can set initial data by using the initialData option of useQuery. This enables you to immediately display default or pre-cached data to users before the data is loaded from the server, thereby enhancing user experience and performance.
How to Use initialData
The initialData option can be directly passed to the useQuery hook. Here is a simple example to illustrate its usage:
jsximport { useQuery } from 'react-query'; function fetchProjects() { return fetch('https://api.example.com/projects').then(res => res.json()); } function Projects() { const { data, isLoading, isError } = useQuery('projects', fetchProjects, { initialData: [{ id: 1, title: 'Initial Project' }] }); if (isLoading) return <div>Loading...</div>; if (isError) return <div>Error!</div>; return ( <div> {data.map(project => ( <p key={project.id}>{project.title}</p> ))} </div> ); }
In the above example, we define a fetchProjects function to fetch project data from the server. In useQuery, we provide an initial data list containing a sample project. This means users will see this initial project before the data is successfully loaded from the server.
Use Cases
Using initialData is particularly suitable for the following scenarios:
- Quick Data Display: When you want the application to show data quickly at startup, rather than waiting for data loading.
- Offline Support: When users are offline, cached data can be displayed.
- Reduce Layout Shifts: By using initial data during asynchronous loading, you can minimize layout changes and improve user experience.
Overall, initialData is a powerful feature that helps developers optimize data loading performance without compromising user experience.