State Management In React
State management is one of the most important topic in React and today we are going to use state in class components and functional components. Before that let’ s learn what state is.
State Management In Class Components
When using the state, the first thing we have to do is create the object. Generally, the state is created in the constructor of a class.
Next, let’ s define some data in state and display them on the page.
I defined name and year in my state. As you can see the name is a string and the year is a number. Now that we have create our state, we can display it.
If we want to display state variable in our html, we use it with curly braces as below.
Our name and year value are static. But in real world projects, we usually do not use it like this. State values are generally change with the user inputs.
In order to adjust the changes in user inputs to state we use setState().
There are some rules that we should pay attention to while using setState(). Some of them are follows:
- Do not directly change a state value. React give us a huge ability to re-render possibility with state. With directly changing a state value, it is inevitable that we will encounter rendering issues.
- Changes that you do in state may be asynchronous. So, after you change state value, if you have to use an updated value, use callback function.
- If you have nested object in your state and want to change specific values in it, first copy the previous state object and then change values that you want to update. In this way you do not lose any unupdated values.
Let’ s say we have a state like the one below:
If we want to update only email info in the contact info, we should update like this:
State Management In Functional Components
In functional component, we define and use state a little bit differently. We have to use the useState() hook to use state.
useState() is a function that takes an initial value for state as a parameter. And returns array with two items. First item is value of a state and second one is a function that updates a state value. And If we want to change state value with user inputs, we can change it like this:
Also we can change specific value of a nested object as below:
Today I tried to explain how we can manage state in class components and functional components in React. I hope my post was helpful to someone.
I wish you have a good day.