In React, useEffect is a React Hook that enables functional components to perform side effects.
Side effects may include data fetching, subscriptions, manual DOM manipulations, or any other operation that isn't purely related to rendering.
useEffect helps manage these side effects in a clean and declarative way.
import React, { useState, useEffect } from 'react'; const YourComponent = () => { const [data, setData] = useState(null); useEffect(() => { fetchData(); }, []); // Empty dependency array means it runs only once (on mount) const fetchData = async () => { try { const response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); const result = await response.json(); setData(result); } catch (error) { console.error('Error fetching data:', error); } }; return ( <div> <p>Data: {data && data.title}</p> </div> ); }; export default YourComponent;
In this example, we have declared the `useEffect` hook and fetched data from the server. The below endpoint will fetch one record from `'https://jsonplaceholder.typicode.com/todos/1'` and once we receive data from API it will assign a response to `setData()` function and with the help of `data` property we are rendering content inside `return()` function.
import React, { useState, useEffect } from 'react'; const YourComponent = () => { const [data, setData] = useState(null); useEffect(() => { // This code runs after the component renders console.log('Component has mounted.'); // Simulate data fetching (replace with actual fetch) const fetchData = async () => { try { const response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); const result = await response.json(); setData(result); } catch (error) { console.error('Error fetching data:', error); } }; fetchData(); // This function will run when the component unmounts return () => { console.log('Component will unmount.'); }; }, []); // Empty dependency array means it runs only once (on mount) // This code runs after every render console.log('Render'); return ( <div> <p>Data: {data && data.title}</p> </div> ); }; export default YourComponent;
`useEffect` is used to perform side effects.
The first argument to useEffect is a function containing the code for the side effect.
The `second` argument is the dependency array. If any value in the dependency array changes between renders, the effect function is `re-run`.
An empty dependency array `[]` means the effect runs once after the initial render (equivalent to `componentDidMount` in class components).
The cleanup function returned from the effect is called when the component is about to unmount (equivalent to `componentWillUnmount` in class components).
The values in the dependency array control when the effect should run. If the dependency array is empty, the effect runs once after the initial render.
If values in the dependency array change between renders, the effect runs again.
useEffect(() => { // Effect code }, [dependency1, dependency2, ...]);
useEffect(() => { // Effect code });
If the effect returns a function, that function will be called when the component unmounts or before the HTML Document is removed from the DOM.
useEffect(() => { // Effect code return () => { // Cleanup code }; }, []);
This is useful for cleanup tasks such as cancelling subscriptions or clearing intervals.
useEffect is a powerful tool for handling side effects in functional components.
It helps separate concerns by keeping side effect logic separate from the component's rendering logic.