Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot assign to read only property 'current' in React useRef

i used react useRef in functional components to get link on html object and store it in Recoil atom. For example:

const Children = () => {
  const [refLink, setSrefLink] = useRecoilState(refLink)
  return <input ref={someRef}/>
}
const Parent = () => {
  const [refLink, setSrefLink] = useRecoilState(refLink)
  const someRef = useRef();
  setSomeRef(someRef)
  return <Children />;
}

export const refLink = atom({
    key: 'refLink',
    default: null ,
});

But when my Parent component ummounts I get error:

react-dom.development.js:20997 Uncaught TypeError: Cannot assign to read only property 'current' of object '#' in file reac-dom.development.js

enter image description here

I can't imagine what's the problem;

like image 437
dendroid Avatar asked Sep 07 '25 20:09

dendroid


1 Answers

If you're getting this error in TypeScript, try listing null in the type annotation, which changes this from a RefObject to a MutableRefObject.

From

const myRef = useRef<MyType>(null)

To

const myRef = useRef<MyType | null>(null)

After doing so, reassigning current should not result in this error (e.g. myRef.current = null).

Source

like image 66
Nelu Avatar answered Sep 09 '25 10:09

Nelu