UNPKG

use-state-ref

Version:

Convert a state to a ref when there need to a indirect use the state

40 lines (29 loc) 974 B
# How to use ```typescript import { useState } from 'react'; import { useStateRef } from 'use-state-ref'; function useSome() { const [state, setState] = useState<string | null>(null); const stateRef = useStateRef(state); const callback = useCallback(() => { if (!stateRef.current) return; setState(prevState => prevState + '?'); }, [stateRef, setState]); return { callback } } ``` When the `state` is change. the `callback` will not re-memoize. You can use this utility. when you need to use a state in a callback but you also need the state does not affect to the callback memoization. This is very simple code. you can use too by just copy the code below. ```typescript import { MutableRefObject, RefObject, useEffect, useRef } from 'react'; export function useStateRef<T>(value: T): RefObject<T> { const ref: MutableRefObject<T> = useRef<T>(value); useEffect(() => { ref.current = value; }, [value]); return ref; } ```