Search code examples
javascriptreactjsuse-effect

Reactjs useeffect function run twice


I don’t get it, could someone please help me with this problem, why is my console.log in my "randomFunc" log out data twice when I visit “Hello” page/component? What is causing the console.log log out second time?

App.js

import { useState } from "react";
import { Switch, Route, Link } from "react-router-dom";
import Home from "./Home";
import Hello from "./Hello";

export default function App() {
  const [data, setData] = useState();

  const randomFunc = (dataFromHelloComponent) => {
    setData(dataFromHelloComponent);
    console.log(dataFromHelloComponent); /* <====  When I click "Go to Hello!" Link, this line log out data twice!? */
  };

  return (
    <div className="App">
      <Link to="/hello">Go to Hello!</Link>
      <Switch>
        <Route path="/" exact component={Home} />
        <Route
          path="/hello"
          render={(props) => (
            <Hello {...props} randomFunc={randomFunc} data={data} />
          )}
        />
      </Switch>
    </div>
  );
}

Hello.js

import { useEffect } from "react";

export default function Hello({ randomFunc }) {
  useEffect(() => {
    randomFunc("Some random data!");
  }, [randomFunc]);

  return (
    <div className="hello">
      <h1>Hello World!</h1>
    </div>
  );
}

when I have “randomFunc” in Hello.js “useEffect” dependency, I get this in my browser console:

Some random data!

Some random data!

and if I remove “randomFunc” from Hello.js “useEffect” dependency, I get this in my browser console:

Some random data!

React warning: React Hook useEffect has a missing dependency: ‘randomFunc’. Either include it or remove the…


Solution

  • You are recreating randomFunc every time App renders. Therefore the function is different, therefore useEffect(..., [randomFunc]) triggers again. You can wrap randomFunc using React.useCallback so it's always the same actual function object returned.