Middle
How do you feel about managing state with libraries like React Query or SWR?
sobes.tech AI
Answer from AI
Libraries like React Query or SWR are excellent for managing state related to asynchronous server requests (API data). They abstract caching, updating, refetching, and data synchronization logic.
Pros:
- Simplify working with server state, reducing the amount of code.
- Automatically update data when changes occur.
- Easily implement optimistic updates and retries.
Cons:
- Not intended for local UI state (e.g., opening modals).
- Can add complexity if used for all state without discernment.
Overall, storing server-related data state via React Query or SWR is a good practice. For UI state, it's better to use local state or specialized managers (Redux, Zustand, etc.).
Example with React Query:
import { useQuery } from 'react-query';
function Users() {
const { data, error, isLoading } = useQuery('users', () => fetch('/api/users').then(res => res.json()));
if (isLoading) return 'Loading...';
if (error) return 'Loading error';
return <ul>{data.map(user => <li key={user.id}>{user.name}</li>)}</ul>;
}