Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useImperativeHandle hook does not update the value

I am using useImperativeHandle hook in my app to give access of value to the parent component:

const [phone,setPhone]=useState("");
 useImperativeHandle(
    ref,
    () => ({
      type: "text",
      name: "phone",
      value: phone
    }),
    [phone]
  );

When I update phone using setPhone, value not going to be updated. What is the problem with my implementation?

like image 547
Hadi Ranjbar Avatar asked Mar 11 '26 14:03

Hadi Ranjbar


1 Answers

useImperativeHandle needs to have the component use forwardRef, Once you do that, you will be able to access the updated ref in the parent since you are providing phone as a dependency to it.

import React, {
  useEffect,
  useState,
  useImperativeHandle,
  forwardRef,
  useRef
} from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const App = forwardRef((props, ref) => {
  const [phone, setPhone] = useState("");
  useImperativeHandle(
    ref,
    () => ({
      type: "text",
      name: "phone",
      value: phone
    }),
    [phone]
  );
  useEffect(() => {
    setTimeout(() => {
      setPhone("9898098909");
    }, 3000);
  }, []);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
});

const Parent = () => {
  const appRef = useRef(null);
  const handleClick = () => {
    console.log(appRef.current.value);
  };
  return (
    <>
      <App ref={appRef} />
      <button onClick={handleClick}>Click</button>
    </>
  );
};
const rootElement = document.getElementById("root");
ReactDOM.render(<Parent />, rootElement);

Working demo

like image 176
Shubham Khatri Avatar answered Mar 13 '26 03:03

Shubham Khatri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!