How to Run useEffect Only Once in React
To run
useEffect only once in React, pass an empty array [] as the second argument. This tells React to run the effect only after the first render, similar to componentDidMount in class components.Syntax
The useEffect hook takes two arguments: a function to run and a dependency array. When the dependency array is empty [], the effect runs only once after the component mounts.
- Effect function: Code to run (e.g., fetching data, setting up a subscription).
- Dependency array: List of variables that trigger the effect when changed. Empty means run once.
javascript
useEffect(() => {
// code to run once
}, []);Example
This example shows a React component that logs a message only once when it first appears on the screen.
javascript
import React, { useEffect } from 'react'; function Welcome() { useEffect(() => { console.log('Component mounted: runs only once'); }, []); return <h1>Hello, welcome!</h1>; } export default Welcome;
Output
Hello, welcome! (and logs 'Component mounted: runs only once' once in console)
Common Pitfalls
Developers often forget the empty dependency array, causing useEffect to run after every render, which can lead to performance issues or infinite loops. Another mistake is including changing variables in the dependency array, which triggers multiple runs.
Wrong way (runs every render):
useEffect(() => {
console.log('Runs every render');
});Right way (runs once):
useEffect(() => {
console.log('Runs only once');
}, []);Quick Reference
Tips to run useEffect only once:
- Always pass
[]as the second argument. - Do not include variables in the dependency array if you want a single run.
- Use this pattern for setup tasks like fetching data or subscriptions.
Key Takeaways
Pass an empty array [] as the second argument to useEffect to run it only once.
Without the empty array, useEffect runs after every render, which is often unwanted.
Use this pattern for initialization tasks like data fetching or event subscriptions.
Avoid adding dependencies if you want the effect to run only on mount.
Remember useEffect runs after the first render, not during rendering.