3 Important Things to Know About State in React

React… We all know the popularity of this framework among developers or programmers. React sit on the top of all the popular JavaScript library. It is really important to understand the concept of React and its different segments.  State which is the heart of React is the most important concept to learn. How it behaves, how it changes and how it works in the different parts of the component. Being a React Developer you should know how to properly use it. You will have to avoid some common pitfalls as you build your application. In this article, we will discuss the five most essential parts of the state. These parts are built upon each other to make you understand the complex topics in React. To make the concepts clear We will discuss many practical examples which you can check on your own.1. State Update With useState Can Not be Merged. When a React developer moves from the class-based component to the function-based component using React hooks, state updates no longer get merged automatically. You can call useState hook as many times as you like to use as many variables as you need. In the example given below…we have a basic form with email and password input. We are going to manage the state for each one of them as individual state variables.Javascriptimport React from “react”;  export default function App() {  const [email, setEmail] = React.useState(“”);  const [password, setPassword] = React.useState(“”);    return (           setEmail(e.target.value)}      />       setPassword(e.target.value)}      />      Submit      );}Now let’s make some changes to the above example. We can manage the form state within a single object. This is going to allow you to call useState just once. Email and password won’t be managed by the individual state variable. Now the question is… How we can update the state with the setState function when it is an object?In form input, we can add onChange prop. This onChange prop will be handled by the generic event handler. Take a look at the code snapshot given below…Javascriptimport React from “react”;  export default function App() {  const [state, setState] = React.useState({    email: ”,    password: ”  })    function handleInputChange(e) {    setState({      [e.target.name]: e.target.value    })  }    return (                      Submit      );}In the above example, the state is getting updated according to the name of the input user is typing currently. This pattern is basically used in the class-based components, but it doesn’t work with the useState hook. When you update the State with useState’s setState function, it doesn’t get merge automatically. What exactly it means…?It simply means that the previous state doesn’t get included whenever we set the state as the user types in. Now, what’s the solution or the option to include the state??  We can do that manually by using the spread operator.Javascriptimport React from “react”;  export default function App() {  const [state, setState] = React.useState({    email: ”,    password: ”  })    function handleInputChange(e) {    setState({            …state,      [e.target.name]: e.target.value    })  }    return (                      Submit      );}2. State Updates Should be ImmutableReact state should be managed and updated in the correct way. To manage the state with the useState hook, you should only use the dedicated setter function, provided as the second element in the array, you get back from the useState to update it. If you don’t do it, and you will try to update it manually using the plain JavaScript example, then you won’t find the expected behavior from your application. Remember that the state updated properly, causes a re-render of our component. Now there is a question…what will happen to the state if we update it in our own way instead of the “React” way. In that case, when something will change, React will take care of displaying and rendering the component. The whole point is…if you update the state with plain JavaScript instead of setState then it won’t trigger a re-render and React will not display the changes in state to the user. In React, it is important to know, how to update state using React which one is the appropriate state hook to fulfill your purposes. You can choose useReducer, useState, or third-party state management library like Redux. You can not update or mutate your state directly.State updates should be immutable always. Mutating your state directly will make your state unpredictable, and it can cause unintended problems in your application. Javascriptimport React from ‘react’;  export default function App() {  const [count, setCount] = React.useState(0);          const newCount = count;        const countPlusOne = count + 1;    return (          Count: {count}      );}3. State Updates Are Asynchronous and Scheduled, It Can Not be Performed ImmediatelyAnother important concept to consider is that state updates are not performed immediately. If you take a look at the React documentation, you will find what exactly happens when you call the setState function. You can use it to update the state variable associated with it. You can take a look at the React documentation and see what exactly happens when you call the setState function. You can use it to update the state variable associated with it. We are told that it accepts a new state value and enqueues a re-render of the component. What does it mean??It means the components are not re-rendered immediately. This happens most usually for performance purposes, and it gives a better idea of what React is doing under the hood.  setState function doesn’t update the state immediately, it merely schedules a state update for some time in the future. It is not easy to look at the code and see exactly when the state update occurred or will occur. This is good for comparing the useRef, which we have mentioned earlier to being able to hold on to the data considering its present property. Updates made with useRef are performed synchronously. Look at the code see exactly when an update was performed in useRef, not with useState.ConclusionAs we have discussed state is the heart of React. When you are working on React, you need to be careful while writing the code. State behavior matters a lot, and it’s important to understand that how you are dealing with state in your React app. The second point in this article is very important to understand. Once you will start working on React and as you will progress you will find yourself doing better in your project. The best thing to understand the state behavior is that break the code and see how things work.