Skip to Content
👆 We offer 1-on-1 classes as well check now
React.jsCore HooksuseEffect Hook

useEffect Hook

The useEffect hook in React is a powerful tool for handling side effects, such as fetching data, setting timers, or manually updating the DOM. It allows you to run some code after rendering a component, making it a crucial part of managing a component’s lifecycle. This hook is a replacement for the componentDidMount, componentDidUpdate, and componentWillUnmount methods in class components.

Basic Example

Let’s start with a simple example that demonstrates how to use useEffect to fetch data from an API when a component mounts:

import { useState, useEffect } from 'react'; function User() { const [user, setUser] = useState(null); useEffect(() => { fetch('https://api.example.com/user') .then(response => response.json()) .then(data => setUser(data)); }, []); // Empty dependency array means this effect runs only once, on mount return ( <div> {user ? ( <p>Welcome, {user.name}!</p> ) : ( <p>Loading...</p> )} </div> ); }

In this example, the useEffect hook is used to fetch user data from an API when the component mounts. The empty dependency array [] ensures that the effect is only run once.

Advanced Usage

For more complex scenarios, you might need to run an effect after every render or when specific values change. Let’s consider an example where we want to update the document title whenever the user’s name changes:

import { useState, useEffect } from 'react'; function Profile() { const [name, setName] = useState('John Doe'); const [age, setAge] = useState(30); useEffect(() => { document.title = `Hello, ${name}`; }, [name]); // Effect runs whenever the name changes return ( <div> <input type="text" value={name} onChange={e => setName(e.target.value)} placeholder="Enter your name" /> <input type="number" value={age} onChange={e => setAge(e.target.value)} placeholder="Enter your age" /> </div> ); }

In this case, the effect is run whenever the name state changes, updating the document title accordingly.

Best Practices

  • Always clean up after your effects to prevent memory leaks. For example, if you set a timer, make sure to clear it when the component unmounts.
  • Be cautious with the dependency array. An empty array [] means the effect runs only once, on mount, while an array with values means the effect runs whenever those values change.
  • Avoid using useEffect for complex computations or heavy operations. Instead, consider using useMemo or useCallback for such tasks.
  • Keep your effects as simple and focused as possible to make your code easier to read and maintain.

Key Takeaways

  • The useEffect hook is used for handling side effects in functional components.
  • The dependency array determines when the effect is run. An empty array means the effect runs once, on mount.
  • Always clean up after your effects to prevent memory leaks.
  • Keep your effects simple, focused, and avoid complex computations or heavy operations within them.
Last updated on