Next.js Discord

Discord Forum

useState when re-render

Unanswered
Greater Swiss Mountain Dog posted this in #help-forum
Open in Discord
Greater Swiss Mountain DogOP
Does the state managed by useState get lost during re-renders?
Even if the initial state provided to useState is updated on re-render, does the state remain unchanged?

24 Replies

You mean giving a starting value to a useState with a initializer function? Or if you’re initializing your useState with a value coming from props?

No, React won’t re-init your state, that’s what useState is for, as long as you don’t unmount and remount the component it’ll keep it’s latest local value (will only change if something calls setState), for React only the first time it’s assigned counts, in the following re-renders that line is ignored
If I couldn’t solve the question, would you mind being a little more specific?
Easy way to test it, just mount <Parent /> anywhere in your app:

// Add the "use client" directive if you're in Next

export function Parent() {
  const [value, setValue] = useState(0);

  useEffect(() => {
    console.log("Parent: " + value);
  }, [value]);

  return (
    <div>
      <p>Parentvalue: {counter}</p>
      <button onClick={() => setValue(value + 1)}>Increment parent counter</button>
      <Child value={value} />
    </div>
  );
}

function Child({ value }: { value: number }) {
  const [counter, setCounter] = useState(value);

  useEffect(() => {
    console.log("Child: " + counter);
  }, [value, counter]);

  return (
    <div>
      <p>Child value: {counter}</p>
      <button onClick={() => setCounter(counter + 1)}>Increment child counter</button>
    </div>
  );
}
@Greater Swiss Mountain Dog solved?
Pteromalid wasp
Of course, it is re-rendered
At first rendering, initial state value and at rerendering, updated state value
:blob_wave:
Greater Swiss Mountain DogOP
@luis_llanes yes ! indeed, initialValue not update when re-render.
@Greater Swiss Mountain Dog <@744377057139753020> yes ! indeed, initialValue not update when re-render.
Was that the issue or I understood it completely wrong?
Pteromalid wasp
No, During useState rendering, state is updated
@Pteromalid wasp No, During useState rendering, state is updated
I'm sorry but I think this user is a bot, or at least acts like one
Pteromalid wasp
Kidding?
Do you want me to explain about useState
I've been working with full stack for over 5 years
Hey
Do you know the correct process of the rendering?
Hello, @luis_llanes , I am here to give you the correct concept of render
And always. React only in initializes the State once, when the component mounts.
Pteromalid wasp
some misunderstanding between us.
I meant, while calling useState hook, update value is called.
Greater Swiss Mountain DogOP
@luis_llanes yes, thanks.
Nice! Mark the answers so other can find the solution as well!