Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent re-render while using custom hooks

Tags:

reactjs

I'm experiencing something similar to this: Should Custom React Hooks Cause Re-Renders of Dependent Components?

So, I have something like this:

const ComponentA = props => {
  const returnedValue = useMyHook();
}

And I know for a fact that returnedValue is not changing (prev. returnedValue is === to the re-rendered returnedValue), but the logic inside of the useMyHook does cause internal re-renders and as a result, I get a re-render in the ComponentA as well.

I do realize that this is intentional behavior, but what are my best options here? I have full control over useMyHook and returnedValue. I tried everything as I see it, caching(with useMemo and useCallback) inside of useMyHook on returned value etc.

Update

Just to be more clear about what I'm trying to achieve:

I want to use internal useState / useEffect etc inside of useMyHook and not cause re-render in the ComponentA

like image 271
MarkKor Avatar asked Jun 27 '26 10:06

MarkKor


1 Answers

I want to use internal useState / useEffect etc inside of useMyHook and not cause re-render in the ComponentA

If you want to avoid the renders triggered by useState() or useEffect() then they are not the right tools.

If you need to hold some mutable state without triggering renders then consider using useRef() instead.

This question has a nice comparison of the differences between useState() and useRef().

Here is a simple example:

const ComponentState = () => {
    const [value, setValue] = useState(0);
    
    return (<>
        <button onClick={() => {
            // Will trigger render
            setValue(Math.random());
        }></button>
    </>);
}
const ComponentRef = () => {
    const valueRef = useRef(0);
    
    return (<>
        <button onClick={() => {
            // Will not trigger render
            valueRef.current = Math.random();
        }></button>
    </>);
}
like image 69
Sly_cardinal Avatar answered Jun 29 '26 22:06

Sly_cardinal



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!