Home > Blockchain >  react useEffect(): Hello only logs one time
react useEffect(): Hello only logs one time

Time:10-27

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>;
    }

CodePudding user response:

The props.visible comes from the parent component so that added depedecy array in useEffect if props.visible change then useEffect call again.

If you add counter as a dependency array and change the counter value so useEffect will called.

Example :

import { useState, useEffect } from "react";

export default function App(props) {
   const [counter, setCounter] = useState(0);

   useEffect(() => {
        console.log("Hello");
   }, [counter]);

  return (
   <div className="App">
     {counter}
    <button onClick={() => setCounter(counter   1)} > Increment </button>

   </div>;
  )
}

CodePudding user response:

Well, props.visible does not change, that is why, if you pass in counter as a dependency to the useEffect, then you should see the output on each change of the counter. (in your case, once more)

CodePudding user response:

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.

CodePudding user response:

You are correct in thinking that the dependency array is the cause of the issue.

If you supply values within the dependency array, then react will only re-render if the supplied values are changed. You have supplied prop.visible, which doesn't update nor cause a re-render to occur.

For this example to be correct then your code would need to look like this:

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

https://reactjs.org/docs/hooks-effect.html

  • Related