React setState + Where does 'prevState' come from?
prevState
is provided by React along withprops
, both of which are optional.- Update 04/13/19: React has changed the setState function documentation by renaming
prevState
toupdater
. The callback function still takes two arguments; thestate
andprops
at the time the change is being applied.
- Update 04/13/19: React has changed the setState function documentation by renaming
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.- Update: I forgot to mention a specific case where it is required to have parenthesis. If you're returning an object without a
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 andfoo: true
is an invalid line. To fix this it must look like() => ({ foo: true })
- Update: I forgot to mention a specific case where it is required to have parenthesis. If you're returning an object without a
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 }));
};