DEV Community

Discussion on: I replaced useState hook with custom one

Collapse
 
shrijan00003 profile image
Shrijan

Awesome, I have tried a similar one for updating state if the component is mounted in typescript-react,

code looks like:

const useStateMounted = <T,>(initialValue: T): [T, React.Dispatch<React.SetStateAction<T>>] => {
  const isMounted = useMounted();
  const [state, setState] = useState(initialValue);

  const newSetState = (value: any) => {
    if (isMounted.current) {
      return setState(value);
    }
  };
  return [state, newSetState];
};

Enter fullscreen mode Exit fullscreen mode

Problems?

  • useStateMounted is not recognized by the eslint-plugin and asking for addition on the dependency array ofuseEffect.