The useEffect hook is a fundamental part of React that lets you perform side effects in function components. It is similar to lifecycle methods in class components such as “componentDidMount”, “componentDidUpdate”, and “componentWillUnmount”. The useEffect hook allows you to run a piece of code (an effect) after the render process. Your code will run on the client side (browser) side instead of the virtual dom.
Within useEffect you can access current elements on the screen as well as other resources such as localStorage, cookie or third party libraries. It is important that you can not access these resources outside useEffect because you are in a virtual dom.
Syntax
import { useEffect } from "react"; useEffect(() => { // Your code goes here }, [dependencies]);
Parameters:
-Effect Function: A function that contains the code you want to execute as a side effect.
-Dependencies: An optional array that specifies when the effect should be re-run. If the dependencies change, the effect will re-run. If you omit this array, the effect will run after every render. If you provide an empty array, the effect will only run once, similar to “componentDidMount”.
Usage
No dependencies: The effect runs after every render.
useEffect(() => { console.log("effect runs after every render"); });
With dependencies: The effect runs only when specified dependencies change.
useEffect(() => { console.log("effect runs when var1 or var2 changes"); }, [var1, var2]);
Empty dependency array: The effect runs only once, after the initial render.
useEffect(() => { console.log("effect runs only once, after the initial render"); }, []);
Cleanup: You can return a function to clean up resources that were used.
useEffect(() => { //get data //process code return () => { //clean up code console.log(“cleanup data”); }; }, [dependencies]);
A full example:
export const MyComponent: FC = () => { const [count, setCount] = useState(0); useEffect(() => { //run after count is rendered console.log(count); return () => { console.log("cleaned up!"); }; }, [count]); //rerun when count is changed return ( <div> <p>Count:{count}</p> <button onClick={() => setCount((prev) => ++prev)}>Increase count</button> </div> ); };
Common use cases
Fetching data: Making API calls and setting the fetched data to state.
Subscriptions: Subscribing to external data sources (like WebSocket or Firebase).
Timers: Setting up intervals or timeouts.
Logging: Logging values or component lifecycle events.
Cleaning up: Cleaning up subscriptions, timers, or any other resources to avoid memory leaks.
Avoid common mistakes
Infinite render loop: This happens when you accidentally set a new value for dependency value.
useEffect(() => { setCount(count + 1); //oops, this will trigger rendering nonstop }, [count]);
Inconsistent dependency value: This is caused by using values that can be changed in every render.
const helloWorld = () => { console.log("Hello world!"); };//this function is re-created on every render useEffect(() => { helloWorld(); }, [helloWorld]);
Summary
The useEffect hook is the most common API when coding with React. It is useful for many scenarios but be careful when using it. It can cause render loop bugs and performance loss (effect code is too heavy). Let’s use it properly and make a nice application!
Reference:useEffect – React
カテゴリー: