DEV Community

loading...
Cover image for Fixing `Deprecated: React.Ref.setCurrent`

Fixing `Deprecated: React.Ref.setCurrent`

idkjs profile image Alain ・1 min read

I keep finding myself having looking this up so I'm writing this note to myself.

Bad Code

This code throws a warning:

let useIsMounted = () => {
  let ref = React.useRef(false);

  React.useEffect0(() => {
    ref->React.Ref.setCurrent(true);
    Some(() => ref->React.Ref.setCurrent(false));
  });
  ref;
};
Enter fullscreen mode Exit fullscreen mode

Warning

Warning 3: deprecated: React.Ref.setCurrent
Please directly assign to ref.current insteadocamllsp
Enter fullscreen mode Exit fullscreen mode

The Fix

In ReasonML/Reason-React

let useIsMounted = () => {
  let ref = React.useRef(false);

  React.useEffect0(() => {
    ref.current = true;
    Some(() => ref.current = false);
  });
  ref;
};
Enter fullscreen mode Exit fullscreen mode

In Rescript

let useIsMounted = () => {
  let ref = React.useRef(false)

  React.useEffect0(() => {
    ref.current = true
    Some(() => ref.current = false)
  })
  ref
}

Enter fullscreen mode Exit fullscreen mode

Yes, they are the same except for the commas which the compiler will remove for you anyway.

Discussion (0)

pic
Editor guide