Hello! Today, we will be unlocking our mastery over states in React.js. Imagine a weather app tracking the changing weather—that's a state in React.js.
A state in React.js is similar to memory. It's knowledge stored by a component and can change over time. States can be either mutable (changeable) or immutable (unchangeable). Consider a game app where your score (state) starts at 0
and increases by 1
with each point:
The score
is our state, and we use setScore
to update it. In the code above, the setScore
function increases the score each time the Score
button is clicked.
Now, let's look closer at the useState
hook. React hooks allow us to use React features within functional components. The hook enables us to create state variables. Consider the following snippet:
