use-state-ref
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

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;
}

Package Sidebar

Install

npm i use-state-ref

Weekly Downloads

394

Version

1.0.0

License

MIT

Unpacked Size

6.04 kB

Total Files

4

Last publish

Collaborators

  • ssen