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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With