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 like a component's memory. It's data stored by a component that can change over time in response to user actions or other events. 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 useState hook enables us to create state variables. Consider the following snippet:
useState(0) initializes our state variable score to 0. It's our initial state. In an online game, each player's initial score would be 0.
This useState hook returns an array with two entries: the current state (score) and a function to update it (setScore). We're using JavaScript's array destructuring to assign names to them. The setScore function lets us change the current score.
We can harness the useState hook with different types of event listeners to create more interactive components. Let's look at an example where the color of a div box changes every time a mouse hovers over it:
In this code, when the mouse hovers over the div (onMouseOver), the background color changes to blue, and it returns to red when the mouse pointer is moved away (onMouseOut).
