The useEffect hook is a fundamental part of React, allowing you to perform side effects in functional components. Here’s a detailed breakdown:
useEffect(() => { // Your side effect code here return () => { // Cleanup code (optional) }; }, [dependencies]);
Effect Function: The first argument is a function that contains the side effect code. This function will run after the render is committed to the screen.
Cleanup Function (optional): The effect function can return a cleanup function that React will call when the component unmounts or before the effect runs again. This is useful for cleaning up subscriptions or timers.
Dependencies Array: The second argument is an array of dependencies. The effect runs only when one of the dependencies changes. If you pass an empty array ([]), the effect runs only once after the initial render (like componentDidMount).
import React, { useEffect, useState } from 'react'; const DataFetchingComponent = () => { const [data, setData] = useState(null); useEffect(() => { fetch('https://api.example.com/data') .then(response => response.json()) .then(data => setData(data)) .catch(error => console.error('Error fetching data:', error)); }, []); // Runs only once after the initial render return{data ? JSON.stringify(data) : 'Loading...'}; };
import React, { useEffect } from 'react'; const EventListenerComponent = () => { useEffect(() => { const handleResize = () => { console.log('Window resized:', window.innerWidth); }; window.addEventListener('resize', handleResize); // Cleanup function to remove the event listener return () => { window.removeEventListener('resize', handleResize); }; }, []); // Runs only once after the initial render returnResize the window and check the console.; };
import React, { useEffect, useState } from 'react'; const TimerComponent = ({ delay }) => { const [count, setCount] = useState(0); useEffect(() => { const timer = setInterval(() => { setCount(prevCount => prevCount 1); }, delay); // Cleanup function to clear the timer return () => clearInterval(timer); }, [delay]); // Runs every time `delay` changes returnCount: {count}; };
The useEffect hook is a powerful tool for handling side effects in functional components, making it essential for modern React development. By understanding its syntax and best practices, you can effectively manage component behavior and side effects.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3