This is the 24th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Translate: beta.reactjs.org/learn/state…

The state variable might look like a regular JavaScript variable that you can read and write. However, State behaves more like a snapshot. Setting it does not change the state variable you already have, but rather triggers rerendering.

In this series of articles you will learn:

  • How do I set state’s trigger for rerender
  • When and how is state updated
  • Why is the state not updated immediately after setting state
  • How event handlers access a “snapshot” of state

Render snapshot of state

We know that setState will trigger a new render, so what happens in the render process?

“Rendering” means React is calling your component (a function). The JSX returned from this function is like a snapshot of the UI. Its properties, event handlers, and local variables are computed using its render state.

Unlike a photo or movie frame, the UI “snapshot” you return is interactive and includes logic like an event handler that specifies what happens in response to the input. React will then update the screen to match the snapshot and connect to the event handler. Therefore, pressing the button triggers a click handler from JSX.

When React rerenders the component:

  • React calls your function again. (So don’t store local variables in functions as they will be reinitialized in render)
  • Your function returns a new JSX snapshot. (based on render state)
  • React then updates the screen to match the snapshot you returned.

As component memory, state is not like a regular variable that disappears when a function returns. State actually “exists” in React itself — like on a shelf! — outside of your function. When React calls your component, it gives you a snapshot of the state of that particular render. Your component returns a UI snapshot in its JSX with a new set of props and event handlers, all computed using the rendered state value!