Hi, I'm Jacob. Enjoying devFlipCards? Buy me a coffee

5. How to pass value from component to it's parent?

An easy way to pass such value up in the components tree is to use useImperativeHandle hook.

It's a function which takes 3 arguments:

  1. reference from forwardRef
  2. callback
  3. dependency array

Value returned from callback is an object, which becomes accessible from parent component. Every change in dependency array causes the object held in reference to update.

Remember - it won't cause parent component to rerender
interface ComponentRef { myValue: number } interface ComponentProps { } const Component = forwardRef<ComponentRef, ComponentProps>((props, ref) => { const [val, setVal] = useState(25); useImperativeHandle(ref, () => { return {myValue: val}; }, [val]); return <div>Child Component</div>; }); interface ParentComponentProps { } const ParentComponent: React.FC<ParentComponentProps> = () => { const ref = useRef<ComponentRef>(null); return <> <Component ref={ref}/> <div onClick={() => { console.info(ref.current?.myValue); // 25 }}>Click here</div> </> }
Struggling to find common date to meet with your friends? Try our new tool
commondate.xyz