prevState() is the same as the setState but the only difference between them is that if we want to change the state of a component based on the previous state of that component, we use this. setState() , which provides us the prevState . Let's check an example of a counter app.
setState() will always lead to a re-render unless shouldComponentUpdate() returns false . To avoid unnecessary renders, calling setState() only when the new state differs from the previous state makes sense and can avoid calling setState() in an infinite loop within certain lifecycle methods like componentDidUpdate .
The reconciliation process is the way React updates the DOM, by making changes to the component based on the change in state. When the request to setState() is triggered, React creates a new tree containing the reactive elements in the component (along with the updated state).
You may call setState() immediately in componentDidMount() . It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render() will be called twice in this case, the user won't see the intermediate state.
prevState
is provided by React along with props
, both of which are optional.
prevState
to updater
. The callback function still takes two arguments; the state
and props
at the time the change is being applied.The parenthesis allow multiple lines where if you didn't use the parenthesis you'd be forced to used a return
. You could use a single line but you don't need the curly braces.
return
statement you must wrap it in parenthesis. Thank you @joedotnot for catching that. So () => {foo: true}
will throw an error because it looks like a function and foo: true
is an invalid line. To fix this it must look like () => ({ foo: true })
Im use this. (Example)
const [modal, setModal] = useState(false);
const [dataAction, setDataAction] = useState({name: '', description: ''});
const _handleChangeName = (data) => {
if(data.name)
setDataAction( prevState => ({ ...prevState, name : data.name }));
if(data.description)
setDataAction( prevState => ({ ...prevState, description : data.description }));
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With