Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop a react functional component (that uses hooks) from re-rendering

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

like image 808
Arshpreet Singh Bhatti Avatar asked Mar 18 '26 12:03

Arshpreet Singh Bhatti


1 Answers

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.

like image 100
mabhijith95a10 Avatar answered Mar 21 '26 02:03

mabhijith95a10



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!