Course Content
React Tutorial
React Tutorial
State and setState()
In React, the state of a component is an object that holds the mutable (i.e. changeable) data for that component. The state is used to store data that is needed to update the user interface in response to user interactions or other events.
Here are some examples of state usage in React:
- Storing form input values: In a form, each input field (such as a text field or checkbox) typically has its own state that is used to store the current value of the field. This state is then used to render the field to the screen and to update the field's value as the user types.
- Managing a toggle or switch: A toggle or switch component (such as a checkbox or radio button) typically has a state that is used to store the current state of the toggle (e.g. "on" or "off"). This state is used to determine the appearance of the toggle on the screen and to update the toggle's state as the user interacts with it.
- Storing a list of items: In a list or table, each item typically has its own state that is used to store the item's data (such as its name, description, and other properties). This state is used to render each item to the screen and to update the item's data as needed.
Here is an example of a state object in a React component:
In the above example, the MyComponent
class extends the React.Component
class and defines a constructor
function that initializes the component's state with a message
property set to the string "Hello, world!" and a count
property set to 0.
The state
object is accessed inside the component's render
method using the this.state
syntax. In this example, the render
method uses the message
and count
properties of the state object to render the user interface.
To update the state object, you can use the setState
method, which is provided by the React.Component
class. Here is an example of how to use the setState
method to update the state object:
In the above example, the handleClick
method is called when the button is clicked, and it uses the setState
method to increment the count
property of the state object by 1. This causes the user interface to update, and the count
value displayed on the page will be incremented by 1 each time the button is clicked.
1. What is state in React?
2. What is the correct way to initialize state in a React component?
3. How do you update the state of a React component?
4. What is the correct way to access the current state of a React component?
Thanks for your feedback!