What is a State?
State is simply data that a component can hold over time, necessary for information that it needs to remember throughout the app's lifecycle.
- It can also be seen as a components memory.
NOTE When updating the components state, it triggers React to re-render the component
Two major things state allows deevelopers to do ๐จโ๐ป๐งโ๐ป
- To update the component's view by re-rendering it.
- To persist local variables between renders.
How to create a state variable with useState().
In order to use state in practice in a component, we must do it in three steps:
- Add a useState() variable
- Use it in the code, usually in JSX
- Update the piece of state in some event handler
Let's see this in action โด๏ธ
- Adding a useState variable
- Using it in the code
- Updating the piece of state in some event handler Firstly, create a function that will carry out the update
Now to use it, we simply write the code below
NOTE The useState function is what we call a hook in React and we can identify hooks in React by the word "use" before the name of the hook. Also we are not to update state variable manually like the code below
However, we are to always use the setCount method as in this example, outside this, React won't know that the state is updated and as a result, the supposed resulting UI doesn't change.