How to locally manage component’s state in ReactJS ?
Component’s local state: Any component is ReactJS majorly depends on its props and state to manage data. A component’s state is private to it and is responsible for governing its behavior throughout its life. A state is nothing but a structure that records any data changes in a react application. It can be used for storing values, form inputs, data from an API, etc. This local state-managed within a component can not be affected by other components.
Approach: To locally manage a component’s state in a class-based component, we instantiate a local state object, which contains all the state variables we need to use in the component. These local state variables can be updated using the setState function. It is important to change the local state only using the setState function as only then will React trigger a component re-render, which is essential for updating the application state.
Create a new React Application:
Step 1: Create a React application using the following command:
npx create-react-app react-local-state
Step 2: After creating your project folder i.e. react-local-state, move to it using the following command:
Project Structure: It will look like the following.
Example: Let’s look at an example to understand how to locally manage a component’s state. In our example, we will consider a value that is initiated as 0. We can update this “value” state by either incrementing it (increase by 1) or decrementing it (decrease by 1). Now to increase or decrease this value, we will use the setState function so as to trigger a component re-render which ensures that any updation to our state (value) will be reflected on the screen.
Step to run the application: Run the application using the following command from the root directory of the project:
Output: Now open your browser and go to http://localhost:3000/, you will see the following output: