useRefState

Access a react state value through a ref.

Implementation

import { MutableRefObject, useRef, useState } from "react";

export const useRefState = <T>(
  initialState: T,
): [T, (newValue: T) => void, MutableRefObject<T>] => {
  const [value, _setValue] = useState<T>(initialState);
  const ref = useRef<T>(initialState);

  const setValue = (newValue: T) => {
    ref.current = newValue;
    _setValue(newValue);
  };

  return [value, setValue, ref];
};

Usage

const MyComponent = () => {
  const [value, setValue, ref] = useRefState(0);
  
  // Print `value` every 1 second
  useEffect(() => {
    const interval = setInterval(() => {
      console.log(ref.current)
    }, 1000);
    
    return () => clearInterval(interval);
  }, []);
  
  return (
    <button onClick={() => setValue(value + 1)}>{value}</div>
  )
}
Last Updated February 23, 2021