usehooks
usehooks copied to clipboard
useVariable hook idea
As addition to the existing useRef hook I think it's useful to have a useVariable hook which mimics the semantics of useState but do not trigger a component rerender. It can be used in any situations where useRef would be used. Like saving the changes in a variable when onChange was called on an outer component.
The useVariable hook could look like:
import { useCallback, useRef } from 'react';
const useVariable = initialValue => {
const ref = useRef(initialValue);
const setter = useCallback(
param => {
ref.current = typeof param === 'function' ? param(ref.current) : param;
},
[ref]
);
return [ref.current, setter];
};
const [variable, setVariable] = useVariable('foobar')
I would love to hear your feedback on that one
Thanks for the idea and sorry for the late reply! I'm a little unclear on the benefit over useRef
. Is it just that you no longer have to remember that the value is stored in ref.current
, as the hook just returns the value instead of the ref?
In my eyes the benefit is that the return value of useVariable is structuraly the same as useState whereas the one rerenders and the other not. With this approach you can easily pass the setter function to another component without altering anything