Data fetching in React
useEffect
is a React Hook that lets you synchronize a component with an external system.
useEffect
is a React Hook that lets you synchronize a component with an external system.
useState
You can use an Effect to fetch data for your component.
Writing data fetching directly in Effects gets repetitive and makes it difficult to add optimizations like caching and server rendering later.
🤔
Voordeel:
Geen kost voor extra dependency
Nadeel:
Syntax komt wat vreemd over
Geen features zoals caching of preloading
useEffect(arg1, arg2)
rg1:
functie die wordt uitgevoerd. Optioneel geeft deze functie een andere functie terug (cleanup functie) die uitgevoerd wordt vóór useEffect
een volgende keer wordt uitgevoerd.arg2:
array van dependencies (= variabelen) waarbij useEffect
opnieuw moet uitgevoerd worden wanneer ze veranderen.useEffect
.then()
of declaratie useEffect
meta.pagination.pageCount
)
Data fetching in React
// Create a client
const queryClient = new QueryClient();
function App() {
return (
// Provide the client to your App
<QueryClientProvider client={queryClient}>
<Todos />
</QueryClientProvider>
)
}
render(<App />, document.getElementById('root'));
function App() {
// ...
}
function MyComponent() {
// Access client
const queryClient = useQueryClient();
const { isPending, isError, data, error } = useQuery({
queryKey: ['swapiPeople'],
queryFn: getSwapiPeople
});
// This is where our UI logic will come
}
render(<App />, document.getElementById('root'));
function App() {
// ...
}
function MyComponent() {
// Access client + execute query here first ...
if (isPending) {
return <span>Loading...</span>
}
if (isError) {
return <span>Error: {error.message}</span>
}
// We can assume by this point that `isSuccess === true`
return (
<ul>
{data.map((people) => (
<li key={people.uid}>{people.name}</li>
))}
</ul>
);
}
render(<App />, document.getElementById('root'));
staleTime
const { isPending, isError, data, error } = useQuery({
queryKey: ['swapiPeople'],
queryFn: getSwapiPeople,
staleTime: 5 * 1000
});