Async & Promiseseasy
How can you implement data fetching in React applications using hooks?
Explain how to effectively use React hooks such as useEffect for data fetching and managing loading states.
Answer
- Using
useEffectHook: Implement theuseEffecthook to handle side effects like data fetching when the component mounts.- Example:
useEffect(() => { fetchData(); }, []);
- Example:
- State Management: Utilize
useStateto manage loading and data state.- Example:
const [data, setData] = useState(null); const [loading, setLoading] = useState(true);
- Example:
- Error Handling: Implement error handling within the fetch process to capture and set error states.
- Cleanup: Use cleanup functions in
useEffectto prevent memory leaks on component unmount.
Source: interview-preparation