You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Got asked during the interview, I didn't know(sad face) so there's the digging:
the 1st one is an updater function you can use when your next state change depends on the last one, then an optional object can be used to when you don't care about the previous state.
setState(updater, [callback])
setState((previousState, currentProps) => {
// state and props are guarueented to be the latest.
return {foo: previousState.foo + currentProps.bar}
}
the formal updater vs the optional object as updater setState({state:1})
the 2nd parameter is a callback will be executed after the setState and re-render so you can do that same operation in componentDidUpdate.
More, setState will always re-render unlesss shouldComponentUpdate return false, so only call setState when the mutable data is different from before when can't do conditional control in shouldComponentUpdate(), to reduce re-renders.
In conclusion: if you need set state base on the previous state, write the updater in a formal way, and if you need to do some sth after the setState use the setState callback or do it in componentDidMount.
The text was updated successfully, but these errors were encountered:
to be consistent with props, e.g. when lifting the state up to a parent, if setState re-render immediately can't delay the reconciliation of the children anymore...
Got asked during the interview, I didn't know(sad face) so there's the digging:
the 1st one is an updater function you can use when your next state change depends on the last one, then an optional object can be used to when you don't care about the previous state.
setState(updater, [callback])
the formal updater vs the optional object as updater
setState({state:1})
the 2nd parameter is a callback will be executed after the setState and re-render so you can do that same operation in componentDidUpdate.
More, setState will always re-render unlesss
shouldComponentUpdate
return false, so only call setState when the mutable data is different from before when can't do conditional control in shouldComponentUpdate(), to reduce re-renders.React docs, Reference2 from medium
to read: why is
setState
asynchronousIn conclusion: if you need set state base on the previous state, write the updater in a formal way, and if you need to do some sth after the setState use the setState callback or do it in componentDidMount.
The text was updated successfully, but these errors were encountered: