Example of useEffect Hook for Effect Management
Example 1: Fetching Data: This React component fetches data from an API when it’s first shown on the screen. It then displays the fetched data or a loading message while waiting.
Javascript
import React, { useState, useEffect } from 'react' ; function MyComponent() { const [data, setData] = useState( null ); useEffect( () => { fetch( 'https://jsonplaceholder.typicode.com/albums/1' ) .then(response => response.json()) .then(data => setData(data)); }, [] ); // No dependencies, run only on mount return ( <div> { data ? <p>Data: {JSON.stringify(data)}</p> : <p>Loading...</p> } </div> ); } export default MyComponent; |
Step to start the Application:
npm start
Output:
Example 2: Setting Up and Cleaning Up Timers:
- Adapt the code to your specific use cases.
- Be mindful of dependency array optimization to avoid unnecessary re-renders.
- Use the cleanup function responsibly to prevent memory leaks or other issues.
By effectively mastering useEffect, you can create well-structured, maintainable, and performant React applications that manage side effects gracefully.
Javascript
import React, { useState, useEffect } from 'react' ; function MyComponent() { const [count, setCount] = useState(0); useEffect(() => { const intervalId = setInterval( () => setCount(count + 1), 1000); // Cleanup function return () => clearInterval(intervalId); }, []); // No dependencies, run only on mount return ( <div> <p> Count: {count} </p> </div> ); } export default MyComponent; |
Step to start the Application:
npm start
Output:
Effect Management with useEffect Hook in React
useEffect serves as a foundational tool in React development, enabling developers to orchestrate side effects within functional components systematically. It facilitates the management of asynchronous tasks, such as data fetching and DOM manipulation, enhancing code organization and maintainability. By defining when these side effects should occur, useEffect promotes a structured approach to development, leading to more robust and scalable applications.