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.