Our application always contains data that we display on the web page. This data can be changed, updated, or deleted. To store this data and ensure it is displayed in its most current form, we use state. You might wonder why not simply use variables? The issue with using plain variables is that, even though we can update them, these changes will not be reflected on our application's page.
In this video, we observe that updating the variable does not result in a visible change, even though the variable itself is updated.
Here is a video demonstrating the concept of state.
If we store our data in the state and modify it, we will see the changes immediately. This is because the state stores our data and triggers a re-render of the page upon any data updates.
React state can store any type of data (e.g. string, object, boolean, array of values, function, etc.)
React has taken care of developers by creating a hook that helps us to work with the state.
useState Hook. Basics
To start working with the useState hook, you should first import it.
To begin using the useState hook, you must initialize it within your functional component.
value is the variable that stores the current state value we wish to track,
setValue is a function that updates this value and triggers a re-render of the function component.
In your React component, you can use as many state variables as you wish. The number depends on the complexity of your component and the nature of the data it manages.
Below, you'll find an example of a React component named SquareComponent. This component demonstrates the use of three distinct state variables to control various aspects of a square's appearance. The state variables include:
color: Manages the background color of the square.
borderRadius: Controls the border radius of the square.
size: Determines the size of the square in pixels.
The component showcases how state in React can be used to dynamically modify the style properties of an HTML element. The changes in the state are reflected immediately in the square's appearance, providing an interactive and visual representation of state management in React.
Level up Frontend skills and advance your career
• Wide range of learning tracks for beginners and experienced developers
• Study at your own pace with your personal study plan
• Focus on practice and real-world experience