0

I set useEffect for only the first time running the console.log("hello");. But when I click the Home link, the useEffect run many times. Why is that? How do I fix it?

https://codesandbox.io/s/relaxed-wildflower-updeh?file=/src/Home.js:95-298

const Home = () => {
  useEffect(() => {
    console.log("hello");
  }, []);

  return (
    <div>
      <h1>History</h1>
      <Link to="/">Home</Link>
    </div>
  );
};
4
  • 1
    what do you mean it runs many times? It only logs after the rendering the component at the moment Commented Jul 31, 2020 at 11:22
  • Your component is remounted after the redirect Commented Jul 31, 2020 at 11:25
  • When I click the Home many times, The logs print many times Commented Jul 31, 2020 at 11:26
  • the '/' route routes back again to home page, so it will run on every render, pretty much expected. Commented Jul 31, 2020 at 11:27

1 Answer 1

3

The useEffect is running every time despite the [] argument because the component itself is mounting/unmounting every time. Why? Because react-router is not properly configured, so it's essentially refreshing the page every time, since react-router isn't there to intercept it. That's likely not what you want — to resolve, you can use history.push() for navigation, but better would be to set up the Router instance itself.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.