What is the second argument that can optionally be passed to setState and what is its purpose?

Technology CommunityCategory: ReactWhat is the second argument that can optionally be passed to setState and what is its purpose?
VietMX Staff asked 3 years ago

A callback function which will be invoked when setState has finished and the component is re-rendered.

Something that’s not spoken of a lot is that setState is asynchronous, which is why it takes in a second callback function. Typically it’s best to use another lifecycle method rather than relying on this callback function, but it’s good to know it exists.

this.setState(
  { username: 'tylermcginnis33' },
  () => console.log('setState has finished and the component has re-rendered.')
)