Ask Your Question
1

What is the method to execute React useEffect hook just once when there is a modification in state?

asked 2023-05-23 20:07:41 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-05-23 20:17:02 +0000

david gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-23 20:07:41 +0000

Seen: 8 times

Last updated: May 23 '23