1

I have got 2 pieces of code one is using independent state in child and the other one with state being send out as props like this in my " sent as props " version.

function App() {
  const [isChanged, setIsChanged] = React.useState(false);
  const [i, setI] = React.useState(0);
  React.useEffect(() => {
    console.log("USEEFFECT");
    setTimeout(() => {
      setIsChanged(true);
    }, 2000);
  }, []);

  return (
    <div className="App zx">
      {isChanged && <h1>Hello CodeSandbox with outter states</h1>}
      <Change set={setI} i={i} />
    </div>
  );
}

the second one with the exception of having states inside <Change /> as such :

function Change() {
  const [i, setI] = React.useState(0);
  let rnd = 9;

  if (i !== rnd) {
    setI(i + 1);
  }

  console.log(i);

The version in which state is managed inside the child, the component runs twice and I get the log two times in a row but in the one with passed down state as props I get the component running once as desired.

  1. Why is this happening and which one is the correct practice ?
  2. When can I safely use state in a child component without worrying about re-renders ?
  3. Is there a way to avoid the re-render in the first version so I get the same results despite using state in the child component ? If so please provide me with a sample.

To reproduce,

  1. Props version : https://codesandbox.io/s/heuristic-driscoll-9m1pl
  2. state in child version : https://codesandbox.io/s/confident-shockley-btjg6
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Hypothesis
  • 1,208
  • 3
  • 17
  • 43
  • 1
    In all probability see https://stackoverflow.com/questions/61578158/why-does-usestate-cause-the-component-to-render-twice-on-each-update – jonrsharpe May 17 '20 at 18:00

1 Answers1

0

Usually you put the state in the component where you want to use it. For example, if just one child uses the state, put it right in the child component. But let's say you want to use the same state in some different child components, then it's better to have it in the parent component. (in this case, it would be better to use useContext() hook). Honestly, I don't understand what you want to accomplish with your code but in general, rendering and re-rendering happens when you update your state. The reason it re-render agin and you see 0 to 9 and again 0 to 9 is that your default state is 0 and each time it get's re-rendered, the state changes to 0. (I assume) Hope this answers some of your questions.

JohnDoe_Scientist
  • 590
  • 1
  • 6
  • 18