Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React hooks: how to instantiate instance variable only once

I would like to derive value from my props using react hooks.
I would like to compute this value only once and not on every render.

This is the first solution I came up with but if props changes z is not re-calculated.


function App(props: { x: number; y: number }) {
    
    const zRef = useRef<number | undefined>(undefined);

    if( zRef.current === undefined ){
    
        //Let's assume the computation of x + y is costly, I 
        //want to avoid doing it every render.
        zRef.current = props.x + props.y;
    
    }

    return (<span>{zRef.current}</span>);

}

The second way I found is this one:


function App(props: { x: number; y: number }) {
    
    const zRef = useRef<number | undefined>(undefined);

    useEffect(()=>{

        zRef.current = props.x + props.y;

    },[props.x, props.y]);

    return (<span>{zRef.current}</span>);

}

But the problem is that zRef.current is undefined on the first render.

Any opinion on the matter much appreciated.

like image 636
Joseph Garrone Avatar asked Nov 01 '25 10:11

Joseph Garrone


1 Answers

Have you tried with useMemo?

useMemo seems to fit your use case, as it allows you to recalculate a value only when any one of the values specified in the dependency array changes.

Like so:

const z = useMemo(() => {
    return props.x + props.y
}, [props.x, props.y])
like image 52
Gian Marco Toso Avatar answered Nov 03 '25 03:11

Gian Marco Toso



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!