useImperativeHandle: This hook customizes the instance value that is exposed to parent components when using ref. It allows you to define methods on the child component that can be called from the parent component.
forwardRef: This is a React higher-order component that allows a parent component to directly interact with a child component's ref. It forwards the ref through the component to one of its child DOM nodes.
State Management:
useState hook is used to create a state variable toggle with an initial value of false.setToggle is the function to update the toggle state.
Forwarding the Ref:
The Button component is wrapped with forwardRef to forward the ref to its internal DOM or methods.Using useImperativeHandle:
Inside useImperativeHandle, we define an object with the method alterToggle.alterToggle method toggles the value of toggle state.
This method will be exposed to the parent component through the ref.
Rendering:
The component renders a button with the text "Button From Child".If toggle is true, it also renders a with the text "Toggle".
Creating a Ref:
useRef hook is used to create a ref called buttonRef. This ref will be used to access the alterToggle method defined in the Button component.Parent Button:
A button is rendered with the text "Button From Parent".When this button is clicked, it calls buttonRef.current.alterToggle(). This triggers the alterToggle method in the Button component, toggling the toggle state.Child Button:
The Button component is rendered with ref={buttonRef}, which forwards the buttonRef to the Button component, making the alterToggle method accessible to the parent.Summary
forwardRef: Allows the parent to pass a ref to the child component.
useImperativeHandle: Exposes custom methods (alterToggle in this case) from the child component to the parent component through the ref.
This pattern is useful when you need to control a child component imperatively, especially when dealing with complex or non-trivial UI interactions that are difficult to achieve through props alone.
Top comments (0)