Reputation: 108
I have a pure functional component where I fetch some data using useEffect. I pass in an empty string to useEffect, so it acts like a component did mount.
const getData = () => {
setTimeout(() => {
setLocalState({ a: 2 });
setIsLoading(false);
}, 0);
};
useEffect(() => getData(), []);
My entire component re-renders twice right now. I want to control this behavior and only re-render with certain conditions.
Here, I want the component to reRender when setLocalState has set the localState but not when setIsLoading has set isLoading to false.
Here's a code sandbox for this problem: https://codesandbox.io/s/0oyp6j506p
Upvotes: 3
Views: 2080
Reputation: 436
If we call multiple state setters outside of react based events will trigger multiple renders but in class components state changes will be batched together. But in long term plan this will be fixed which is mentioned here
This appears to be normal React behavior. It works the exact same way if you were to call setState() in a class component multiple times.
React currently will batch state updates if they're triggered from within a React-based event, like a button click or input change. It will not batch updates if they're triggered outside of a React event handler, like a setTimeout().
I think there's plans long-term to always batch events, but not sure on the details.
Upvotes: 1