React State
Explore React state management by learning how to use the useState hook to create interactive components. Understand array destructuring in JavaScript and how to update and display state changes within your React application. This lesson guides you through handling user input and re-rendering components with updated state.
We'll cover the following...
React Props are used to pass information down the component tree; React state is used to make applications interactive. We’ll be able to change the application’s appearance by interacting with it.
As part of this react hooks tutorial, we will first explore a utility function called React useState that we use for managing state. In React, a function like this is called a “hook.” There is more than one React hook related to state management and other features, and you will learn about them throughout the next sections. For now, let’s focus on the React useState hook:
React’s useState hook takes an initial state as an argument. We’ll use an empty string, and the function will return an array with two values. The first value (searchTerm) represents the current state; the second value is a function to update this state (setSearchTerm). I will sometimes refer to this function as state updater function.
If you are not familiar with the syntax of the two values from the returned array, consider reading about JavaScript array destructuring. It is used to read from an array more concisely. This is array destructuring and its benefits visualized in a nutshell:
In the case of React, the React useState hook is a function which returns an array. Take again the following JavaScript example as comparison:
Array destructuring is just a shorthand version of accessing each item one by one. If you express it without the array destructuring in React, it becomes less readable:
The React team chose array destructuring because of its concise syntax and ability to name destructured variables. The following code snippet is an example of array destructuring:
After we initialize the state and have access to the current state and the state updater function, use them to display the current state and update it within the App component’s event handler:
The following code is the complete demonstration of the above concepts: