[Feature Request]: useStateRef
behnammodi opened this issue · comments
I start with an example:
const [count, setCount] = useState();
useEffect(() => {
const handleVisibiltuy = () => {
console.log(count);
};
document.addEventListener('visibilitychange', handleVisibiltuy);
return () => document.removeEventListener('visibilitychange', handleVisibiltuy);
}, [count]);
Imagine we have the above code, what is a problem? problem is React runs useEffect
inside function every time count
changes, but might we don't need to know updated count's value until visibilitychange
event happens.
we can have a new hook like this:
function useStateRef<T>(initialValue: T): [T, (nextState: T) => void, () => T] {
const [state, setState] = useState(initialValue);
const stateRef = useRef(state);
stateRef.current = state;
const getState = useCallback(() => stateRef.current, []);
return [state, setState, getState];
}
and we can change exmaple code to this:
const [count, setCount, getCount] = useStateRef();
useEffect(() => {
const handleVisibiltuy = () => {
console.log(getCount());
};
document.addEventListener('visibilitychange', handleVisibiltuy);
return () => document.removeEventListener('visibilitychange', handleVisibiltuy);
}, []);
So, we could remove count
from useEffect
dependence and useEffect
inside function just run once
Also, this hook is very useful for useCallback
, please see this exmaple:
const [count, setCount] = useState();
const handleClick = useCallback(() => {
console.log(count);
}, [count]);
we can change to
const [count, setCount, getCount] = useStateRef();
const handleClick = useCallback(() => {
console.log(getCount());
}, []);
useStateRef
is just a name and we can have a better name for that
Hi, thanks for your suggestion. RFCs should be submitted as pull requests, not issues. I will close this issue but feel free to resubmit in the PR format.
@gaearon Thanks, I opened a new one facebook/react#22169
Sorry that’s not what I was suggesting. This is the correct repository for RFCs (not the React one!) but the RFCs need to be opened as pull requests (not issues). Please read the README which explains the process.