Q1. How do you manage loading state in React?
Use a boolean state variable like isLoading. Set it to true before the request starts, and false after completion. Conditionally render a loading spinner or skeleton while true.
Q2. How do you handle error states?
Use an error state variable. Set it when a request fails. Then conditionally render an error message. Optionally, provide a retry button to refetch.
Q3. What is a typical pattern for data fetching with loading/error?
In the component, have states for data, loading, and error. In useEffect, set loading true, then fetch, on success set data and loading false, on error set error and loading false. Render based on these states.
Q4. How do you avoid memory leaks when setting state after unmount?
Use a flag (e.g., mounted) or AbortController to cancel requests. In cleanup, set a variable to false and check before setting state, or cancel the request.
Q5. Can you use a custom hook for data fetching?
Yes, create a custom hook like useFetch that encapsulates data, loading, and error logic. It can take a URL and options, and return the states. This promotes reusability.
