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> </> }
devFlipCards 2024

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.