UseEffect Hook in react js

UseEffect Hook in react js

useEffect is a React hook that allows you to perform side effects in your functional components. Side effects are actions that are performed outside of the component, such as updating the document title or making an API call.

Here's an example of how to use useEffect to update the document title when a count state variable changes:

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

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

  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);

  const increment = () => setCount(count + 1);
  const decrement = () => setCount(count - 1);

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={increment}>+</button>
      <button onClick={decrement}>-</button>
    </div>
  );
}

In this example, we're using the useState hook to create a count state variable, which starts at 0. We're also using the setCount function returned by the useState hook to update the count value when the user clicks the + or - button.

We're using the useEffect hook to update the document title every time the count value changes. The useEffect hook takes two arguments: a function to perform the side effect, and an array of dependencies that determine when the effect should run. In this case, we're passing [count] as the second argument, which means that the effect should run whenever the count value changes.

The function passed to useEffect updates the document title to include the current count value. Now, every time the user clicks the + or - button, the count value will update, and the useEffect hook will run to update the document title accordingly.

Note that if you don't provide a second argument to useEffect, the effect will run on every render of the component, which can be inefficient. By specifying the dependencies, you can ensure that the effect only runs when necessary.

Did you find this article valuable?

Support Sawan Kumar Jha by becoming a sponsor. Any amount is appreciated!