Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To execute React useEffect hook just once when there is a modification in state, you can pass an empty array as the second parameter of the useEffect hook. This means that the effect will only be executed once when the component initially renders, and not re-run on subsequent renders.

For example:

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

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

  useEffect(() => {
    // This will run only once on component mount
    console.log("Effect executed");
  }, []);

  const handleClick = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleClick}>Increment count</button>
    </div>
  );
}

In the above example, the useEffect hook will run only once when the component mounts, and not re-run when the count state changes.