Making a Value Persistent
Explore how to make a value persistent in React function components by using global state variables and custom getter-setter methods. Understand how to link state across multiple updates, handle user actions, and trigger re-renders to maintain consistent UI state.
We'll cover the following...
Persisting the value
JavaScript supports function scope, which means that variables defined inside a function cannot be accessed from outside the function. As a result, each function has its own scope. If we invoke a function multiple times, there'll be multiple scopes. However, no matter how many times we invoke it, it wouldn't create a different output.
For our count value, we can visualize what happened with the two updates in two different scopes in the figure below.
Luckily, JavaScript supports a function scope in a way that it can access all variables defined inside the scope in which it is defined. In our case, if a variable is defined outside of the Title function (template provided below), we can ...