1.0.0 • Published 4 years ago

use-state-ref v1.0.0

Weekly downloads
5
License
MIT
Repository
github
Last release
4 years ago

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