Search code examples
reactjsuse-effect

react useEffect(): Hello only logs one time


I wonder why 'Hello' is only logged once, since there is setCounter(1) which will trigger re-render, for me 'Hello' will be logged twice. Maybe there is something to do with the dependency array? Since props.visible is not passed, useEffect() will only run one time?

Here is my CodeSandBox: https://codesandbox.io/s/peaceful-brattain-hw0mm?file=/src/App.js:23-287

Any help is appreciated.

import { useState, useEffect } from "react";

    export default function App(props) {
      const [counter, setCounter] = useState(0);
      useEffect(() => {
        console.log("Hello");
        setCounter(1);
      }, [props.visible]);
      return <div className="App">{counter}</div>;
    }

Solution

  • The function inside useEffect runs one time on initial render and then every time when the value(s) in dependency array change. If props.visible doesn't change the useEffect is not triggered even if the component rerendered due to state change.