Explain: Normally, variables “disappear” when the function exits but state variables are preserved by React

460 Views Asked by At

Normally, variables “disappear” when the function exits but state variables are preserved by React

1- Does this mean that the state is preserved when the component unmounts ?

2- If yes, does this means that when this component is ready to be mounted again, Its state gets Its old value rather than being Initialized ?

1

There are 1 best solutions below

0
Piyush Rana On BEST ANSWER

The answer to your first point is simply NO when component unmounts all preserved state will disappear. React preserve state in order to serve same state value when a functional component re-renders. If you declare your state in a variable, you'll see that variable each time component re-renders re-initialized.

I think answer to your second point should be clear from first point.