Home > Software engineering >  Confused about basic state and props in React
Confused about basic state and props in React

Time:01-02

Let's suppose I have two components i.e. "Parent" which contains two state variables and a child "Child" to which these two variables are passed.

export default function Parent() {
  const [a, setA] = React.useState(1);
  const [b, setB] = React.useState(2);

  const inc = () => {
    setA(a   1);
    setB(b   1);
  }

  return (
    <div>
      <Child a={a} b={b} />
      <button onClick={inc}>Inc</button>
    </div>
  );
}
export function Child({ a, b }) {
  console.log(a, b);
  const [inA, setInA] = React.useState(a || -1);
  const [inB, setInB] = React.useState(b || -1);

  return (
    <div>
      <div>{inA}</div>
      <div>{inB}</div>
    </div>
  );
}

My understanding was that as soon as the props passed on to Child are changed it will re-render and hence both inA and inB will get newer defaults but it does not happen. Why is that?

Relevant Stackblitz link.

CodePudding user response:

My understanding was that as soon as the props passed on to Child are changed it will re-render and hence both inA and inB will get newer defaults

Yes, it will re-render but inA & inB don't reinitialize with new props. Note that the first argument you pass to useState is only used once for the first initialization of the state. After that, your useState will keep the current state across the re-renders and will update it when you call setInA or setInB

  • Related