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.
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])
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With