Home > front end >  React useRef reset current value when component unmouted
React useRef reset current value when component unmouted

Time:01-01

I am calling a useRef hook to refer to two components, but I am facing a problem that if either of those components unmounted then useRef won't work.

Code below:

const ref = useRef();

const handleFocusInput = () => {
  ref.current.focus();
}

// both input components use the same useRef() hook
<Input ref={ref} onFocusInput={handleFocusInput} /> 


// Modal will be destroyed on close and the Input component inside Modal will be destroyed as well
<Modal onClose={() => setCloseModal()}> 
  <Input ref={ref} onFocusInput={handleFocusInput} />
</Modal>

Input component:

const Input = forwardRef((props, ref) => {
   return (
     <>
       <button onClick={props.onFocusInput}>Click to focus input</button>
       <input ref={ref} type="text" />
     </>
   )
})

When I closing Modal, the current.value of useRef() will be reset to undefined and so it causing an error TypeError: Cannot read properties of null (reading 'focus') when I am clicking to the button in Input to trigger onFocusInput.

I want to keep ref still working even if one of them Input component is destroyed. How I can resolved it?

CodePudding user response:

Focusing on solving your problem and not the code, I think you want a single Input component instead:

const inputRef = useRef();

const handleFocusInput = () => {
  inputRef.current.focus();
};

const input = <Input ref={inputRef} onFocusInput={handleFocusInput} />;

<>
  {input}
  <Modal onClose={() => setCloseModal()}>{input}</Modal>
</>
  • Related