Skip to content

[Feature Request]: useStateRef #199

Description

@behnammodi

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

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions