Skip to main content

useEffect

The useEffect hook is a powerful tool in React that allows you to perform side effects in functional components. Side effects could be anything from fetching data and updating the DOM to subscribing to an event or manually changing the document title. Before hooks, these side effects were handled in lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount in class components.

Basic Syntax

The basic syntax of useEffect is as follows:

useEffect(() => {
// Your side-effect code here.
}, [dependencies]);
  • The first argument is a function where you put your side-effect logic.
  • The second argument is an optional array of dependencies.

How it Works

  1. Mounting: When the component mounts, the code inside useEffect runs.

  2. Updating: If the dependency array is provided, the code will run again whenever any dependency changes.

  3. Unmounting: If you return a function within useEffect, it will be executed when the component unmounts, acting like a cleanup function.

Examples

Without Dependencies

If you don't provide the dependency array, the effect will run after every render, including the first one.

useEffect(() => {
console.log('This will run after every render');
});

With Empty Dependencies

If you provide an empty array [] as the second argument, the effect will only run once after the initial render, similar to componentDidMount.

useEffect(() => {
console.log('This will run once after the initial render');
}, []);

With Dependencies

If you provide variables inside the dependency array, the effect will run whenever those variables change.

const [count, setCount] = useState(0);

useEffect(() => {
console.log(`Count has changed to ${count}`);
}, [count]);

Cleanup

You can also return a function from useEffect to specify how to clean up after the effect, similar to componentWillUnmount.

useEffect(() => {
const subscription = someSubscribeFunction();

return () => {
someUnsubscribeFunction(subscription);
};
}, []);

Conditional Effects

You can have conditional effects by placing conditions inside your useEffect.

useEffect(() => {
if (someCondition) {
// Do something
}
}, [someCondition]);

Multiple Effects

You can use multiple useEffect hooks in a single component to separate concerns.

useEffect(() => {
// Handle user authentication
}, [auth]);

useEffect(() => {
// Fetch initial data
}, []);

Async Operations

If you want to perform asynchronous operations inside useEffect, you can define an async function inside it and immediately call that function.

useEffect(() => {
const fetchData = async () => {
const result = await someAsyncOperation();
// Do something with the result
};

fetchData();
}, []);

Summary

The useEffect hook provides a versatile way to handle side effects in your React functional components. It replaces lifecycle methods in class components, offering a more intuitive and flexible API.

Live Editor
Result
Loading...

Observattions

  • The useEffect would trigger and print 1) >>>---> The count value from use effect: 0 as it would execute once, as it is first executed by this time count is zero so it would print zero
  • Click on Increase button would increase the count value and prints The count value is ???, where ??? is updated count
  • Click on Effect Count button would trigger click handler, but due to count value was set to 0 when it excuted for first time it would still print 1) >>>---> The count value from use effect: 0

To get updated count value we need to make sure the useEffectHanlder triggered every time count value change, Now observe below example

Live Editor
Result
Loading...

We were passing count in useEffect(useEffectHanlder, [count])