Understanding React useEffect hook

December 10, 2020

The useEffect hook is a powerful tool in React for handling side effects in function components. It works similarly to lifecycle methods in class components, providing a way to execute code at specific points in a component's lifecycle.

In class components, lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount are used to perform side effects such as data fetching, subscriptions, and manual DOM manipulations. The useEffect hook combines these capabilities into a single API for functional components.

The useEffect hook accepts two arguments: a function and an array of dependencies. The function passed to useEffect runs after the component renders. To run the effect only once when the component mounts, pass an empty array as the second argument. To run the effect whenever specific props or state variables change, include those variables in the array.

Here is a simple example demonstrating how the useEffect hook works:

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

export default function Counter() {
  const [counter, setCounter] = useState(0);

  useEffect(() => {
    console.log('Component mounted!');

    return () => {
      console.log('Component unmounted!');
  }, []);

  useEffect(() => {
    console.log(`Counter has changed to: ${counter}`);
  }, [counter]);

  return (
      <p>Counter: {counter}</p>
      <button onClick={()=> setCounter((prevCounter)=> prevCounter + 1)}>Increment</button>