I start with an example:
const[count,setCount]=useState();useEffect(()=>{consthandleVisibiltuy=()=>{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:
functionuseStateRef<T>(initialValue: T): [T, (nextState: T) =>void,()=>T]{const[state,setState]=useState(initialValue);conststateRef=useRef(state);stateRef.current=state;constgetState=useCallback(()=>stateRef.current,[]);return[state,setState,getState];}and we can change exmaple code to this:
const[count,setCount,getCount]=useStateRef();useEffect(()=>{consthandleVisibiltuy=()=>{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();consthandleClick=useCallback(()=>{console.log(count);},[count]);we can change to
const[count,setCount,getCount]=useStateRef();consthandleClick=useCallback(()=>{console.log(getCount());},[]);useStateRef is just a name and we can have a better name for that
I start with an example:
Imagine we have the above code, what is a problem? problem is React runs
useEffectinside function every timecountchanges, but might we don't need to know updated count's value untilvisibilitychangeevent happens.we can have a new hook like this:
and we can change exmaple code to this:
So, we could remove
countfromuseEffectdependence anduseEffectinside function just run onceAlso, this hook is very useful for
useCallback, please see this exmaple:we can change to
useStateRefis just a name and we can have a better name for that