Reputation: 125
I'm looking into an expo barcode scanner and in their example they have a function running after a setState hook. I would just like to understand why it's about to run after the hook is called because my understanding was once setState hook is called it rerenders the component.
I'm referring to the function handleBarCodeScanned. How is the alert being called after setScanned(true)?
Upvotes: 1
Views: 69
Reputation: 187272
Setting state is asynchronous. This is because you may set multiple bits of state in some event handler. You could, for instance:
const handleBarCodeScanned = ({ type, data }) => {
setScanned(true);
setData(data);
setScanType(type);
};
Then after everything is done executing the component will re-render with all the state that just got changed. Internally, react just marks that component as needing an update when you change state, and (very briefly) later it starts actually doing the render.
So because it keeps executing after you change state, you can also do other stuff after you change state. Like show an alert, or start an HTTP request, or whatever your application needs.
Upvotes: 2