use-state-ref
v1.0.0
Published
Convert a state to a ref when there need to a indirect use the state
Downloads
2,728
Readme
How to use
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.
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;
}