Sunday, 1 February 2026

How to use useEffect hook in React

React is a Javascript library used to build modern fast and scalable User Interfaces(UI).

React Hooks are functions that provides developers to use state and handle lifecycle in the functional components effectively and efficiently without needing to writing class components while making code cleaner and reusable.

In this tutorial some light is thrown on useEffect(), a functional component react hook.

useEffect() let developers initiate side effects in functional component, such as fetching data, setting event listeners and manipulating the DOM. They initiate events when the components are mounted, when the components are updated and when the components are unmounted alike lifecycle methods in class components (componentDidMount, componentDidUpdate, and componentWillUnmount).


Syntax:

useEffect(setup function, dependencies?)

  • setup function: It is commonly an anonymous function(unnamed) containing the Effect's logic which is called on component's different lifecycles. It may also optionally return a cleanup anonymous function which is called commonly when the component is unmounted.
  • dependencies:  It is an array which can include props, component's state, and all variables and functions declared inside the component's body. Every time the state of the dependencies changes, the component's setup function runs.
Example with skipping dependency, the second parameter:
import { useState, useEffect } from 'react';

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

  useEffect(() => {
    setTimeout(() => {
      setCount((count) => count + 1);
    }, 1000);
  });        //useEffect without dependencies

  return <h1>I've rendered {count} times!</h1>;
}
When the second parameter is skipped in useEffect hook as in above example, the setup is executed on every render, in above case it re-renders after every 1000 millisecond(a second).

Example including empty dependency as the second parameter:

useEffect(() => { 
}, []);    // runs setup function only on the first render of component


Example including dependencies in the second parameter:

useEffect(() => {

}, [prop, state]);     // runs on the first render and any time  dependency value changes,        dependency could be prop, or component's state or even may be function


The Effect Cleanup example:

const Timer = () => {

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

  useEffect(() => {

function    let timer = setTimeout(() => {

      setCount((count) => count + 1);

    }, 1000);

    return () => clearTimeout(timer)    // the cleanup function mitigating memory leak

  }, []);

  return <h1>Rendered {count} times!</h1>;

}

No comments:

Post a Comment