Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Not quite, having to use for current everywhere is just annoying, and it doesn't allow for a one-time constructor function.


Why do you have to use current everywhere? You can do const { current: myStableValue } = useRef(computation);

Not sure what you mean by one time constructor function, but you can pass the result of a function to initial value.

const { current: myStableValue } = useRef((() => { //called once })());


This is incorrect. useRef takes an initialValue argument, but it does not treat functions as lazy initializers like useState does. If you pass a function to useRef, you’re just going to get that function as the initial value.

If you want to lazily initialize a ref, you need to manually check if it has been initialized and run your expensive code if it hasn’t. Dan Abramov provides what appears to be a pattern officially recommended by the React team: https://github.com/facebook/react/issues/14490#issuecomment-...


I always do `const [stableValue] = useState(() => ...)`. It’s clear, simple, and easy to promote to an interactive value.


It's not a function, it's an immediately-invoked function expression.

Edit: I guess it would be a bit inefficient to invoke the IIFE every render just to initialize the value once. Probably better to use useMemo with [] as the dependency list then, either one achieves the same result.


I missed that you were immediately invoking the function expression. But yes, that doesn't save you from running the expensive calculation every subsequent render.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: