Mohamed Ajmal P
Posted on May 31, 2022
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,
};
Then update state look like this,
this.setState({
hasBeenClicked: true
})
If the initial value is like more than values in object ,
this.state = {
theme: 'blue',
addressInfo: {
street: null,
number: null,
city: null,
country: null
},
}
- Update theme like this,
this.setState({
theme: ‘red’,
})
- Update addressInfo like this,
this.setState({
addressInfo: {
...this.state.addressInfo,
city: "New York City",
},
});
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
)
Updating State in functional component
Basic structure
const MyComponent = () => {
const initialState = () => 1;
const [value, setValue] = useState(initialState);
};
Using Multiple State Values
const [value, setValue] = useState({foo: "bar"});
setValue({foo: "foobar"});
const [value, setValue] = useState({foo: "bar", test: “demo”});
setValue({...value, foo: "foobar"});
Or
setValue(prev => {...prev, foo: "foobar"});
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.
Posted on May 31, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 8, 2024