What is useEffect in ReactJs with Example?

What is useEffect in ReactJs with Example?

In React.js, theuseEffect hook is used to perform side effects in function components. Side effects can include data fetching, subscriptions, manual DOM manipulations, and more. It is a replacement for lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount in class components.

Here's a basic example of useEffect:

import React, { useState, useEffect } from 'react';

function ExampleComponent() {
  // State variable
  const [count, setCount] = useState(0);

  // useEffect hook
  useEffect(() => {
    // This code will run after the first render
    console.log('Component did mount');

    // You can perform side effects here

    // Clean-up function (componentWillUnmount)
    return () => {
      console.log('Component will unmount');
      // You can perform clean-up here
  }, []); // The empty dependency array means this effect runs only once, similar to componentDidMount

  return (
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>

export default ExampleComponent;

In this example:

  • The useEffect hook is called with a function as its first argument. This function contains the code for the side effect.

  • The second argument of useEffect is an array of dependencies. If the dependencies change between renders, the effect will re-run. An empty array [] means the effect runs once after the initial render (similar to componentDidMount in class components).

Inside the useEffect:

  • We log "Component did mount" to the console after the first render.

  • We have a clean-up function (returned from useEffect). This clean-up function runs before the component is unmounted or before the effect runs again due to a change in dependencies.


The example also includes a simple button that increments the count state. The component re-renders when the state changes, but the useEffect won't run again because it has an empty dependency array. The clean-up function is printed when the component is unmounted or when the dependencies change.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!