Search code examples
reactjscomponentsstatemountreact-component-unmount

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


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 ?


Solution

  • 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.