constChild=forwardRef((props,ref)=>{const[color,setColor]=useState("red");// To customize the value that the parent will get in their ref.current:
// pass the ref object to useImperativeHandle as the first argument.
// Then, whatever will be returned from the callback in the second argument,
// will be the value of ref.current.
// Here I return an object with the toggleColor method on it, for the parent to use:
useImperativeHandle(ref,()=>({toggleColor:()=>setColor(prevColor=>prevColor==="red"?"blue":"red")}));return<divstyle={{backgroundColor:color}}>yo</div>;});classParentextendsComponent{childRef=createRef();handleButtonClicked=()=>{// Ref passed to a function component wrapped in forwardRef.
// Note that nothing has changed for this Parent component
// compared with the class component in example 2!
this.childRef.current.toggleColor();}render(){return(<div><buttononClick={this.handleButtonClicked}>togglecolor!</button><Childref={childRef}/></div>);}}