Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do you know what's the second parameter of setState? #1

Open
yeecai opened this issue May 19, 2020 · 2 comments
Open

Do you know what's the second parameter of setState? #1

yeecai opened this issue May 19, 2020 · 2 comments

Comments

@yeecai
Copy link
Owner

yeecai commented May 19, 2020

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.

this.setState({ theState: theValue}, ()=> doSthAfterStateChange() )

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 asynchronous

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.

@yeecai
Copy link
Owner Author

yeecai commented May 22, 2020

Ok, because

  1. delaying reconciliation is beneficial, but why???
  2. 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...

@yeecai
Copy link
Owner Author

yeecai commented Jun 3, 2020

Ok can prioritize a bit of UI update

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant