useShadowedState.ts 688 B

123456789101112131415161718
  1. import { useState, useEffect } from 'react';
  2. import { usePrevious } from 'react-use';
  3. export function useShadowedState<T>(outsideVal: T): [T, (newVal: T) => void] {
  4. const [currentVal, setCurrentVal] = useState(outsideVal);
  5. const prevOutsideVal = usePrevious(outsideVal);
  6. useEffect(() => {
  7. const isOutsideValChanged = prevOutsideVal !== outsideVal;
  8. // if the value changes from the outside, we accept it into the state
  9. // (we only set it if it is different from the current value)
  10. if (isOutsideValChanged && currentVal !== outsideVal) {
  11. setCurrentVal(outsideVal);
  12. }
  13. }, [outsideVal, currentVal, prevOutsideVal]);
  14. return [currentVal, setCurrentVal];
  15. }