1.

What Is The Second Argument That Can Optionally Be Passed To Setstate And What Is Its Purpose?

Answer»

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.')
)

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.')
)



Discussion

No Comment Found