DEV Community

Cover image for React Updating State
Mohamed Ajmal P
Mohamed Ajmal P

Posted on

React Updating State

Overview

In this code along, we'll discuss updating state in React.

Objectives

  • Update state in class component
  • Update state in functional component

Updating State in class component

If the initial value like this,

this.state = {
     hasBeenClicked: false,
};
Enter fullscreen mode Exit fullscreen mode

Then update state look like this,

this.setState({
    hasBeenClicked: true
})
Enter fullscreen mode Exit fullscreen mode

If the initial value is like more than values in object ,

this.state = {
  theme: 'blue',
  addressInfo: {
    street: null,
    number: null,
    city: null,
    country: null
  },
}
Enter fullscreen mode Exit fullscreen mode
  • Update theme like this,
this.setState({
    theme: ‘red’,
})
Enter fullscreen mode Exit fullscreen mode
  • Update addressInfo like this,
this.setState({
  addressInfo: {
    ...this.state.addressInfo,
    city: "New York City",
  },
});
Enter fullscreen mode Exit fullscreen mode

Call a function after state has been updated

  this.setState({
    hasBeenClicked: true
 },
   //This callback will fire once the state has been updated
  () => console.log(this.state.hasBeenClicked)// prints true
) 
Enter fullscreen mode Exit fullscreen mode

Updating State in functional component

Basic structure

const MyComponent = () => {
    const initialState = () => 1;
    const [value, setValue] = useState(initialState);
};

Enter fullscreen mode Exit fullscreen mode

Using Multiple State Values

const [value, setValue] = useState({foo: "bar"});
setValue({foo: "foobar"});

Enter fullscreen mode Exit fullscreen mode
const [value, setValue] = useState({foo: "bar", test: “demo”});

setValue({...value, foo: "foobar"});
Or
setValue(prev => {...prev, foo: "foobar"});
Enter fullscreen mode Exit fullscreen mode

Conclusion

React’s useState() hook makes functional components more powerful by allowing them to possess state. You can set an initial value, access the current value with an assurance it’ll persist between re-renders, and update the state using a specially provided function.

Stateful functional components are often quicker to write than their class-based counterparts. Moreover, they can make it more obvious what’s going on in your codebase as the references to state and setState() are eliminated in favour of clear variable names. Ultimately, useState() provides flexibility and means you no longer need to convert functional components to class components the moment you require state.

Top comments (0)