Use useImperativeHandle for Direct Control in React

You click a button in the parent… But you want to control something inside the child 😐 Like: Focus an input Reset a form Open a modal And suddenly… you’re stuck. 🤔 The Problem React works in a clean way: Parent → passes data Child → sends events back But sometimes you need direct control over a child component. Using props for this: Adds unnecessary state Makes logic confusing Feels like overengineering 💡 The Solution: useImperativeHandle useImperativeHandle lets the child expose specific functions to the parent using ref. So instead of forcing everything through props… you give controlled access where needed. ⚙️ How It Works Parent creates a ref Passes it with forwardRef Child decides what to expose 🧠 Example import { forwardRef, useImperativeHandle, useRef } from "react"; const Input = forwardRef((props, ref) => { const inputRef = useRef(); useImperativeHandle(ref, () => ({ focus: () => { inputRef.current.focus(); } })); return <input ref={inputRef} />; }); export default Input; Now parent can do: inputRef.current.focus(); 🚀 When to Use It? Input focus control Modals / dropdowns Animations Third-party libraries ⚠️ Rule Don’t use it everywhere. Only when props start making things messy. 🧩 Final Thought React is declarative… But sometimes, a little direct control makes life easier. Have you ever faced this situation? 😄 #ReactJS #JavaScript #FrontendDevelopment #WebDevelopment #ReactHooks #useImperativeHandle #SoftwareDevelopment #CodingTips #LearnToCode #ReactDevelopers #MERNStack #FrontendEngineer #DevCommunity #Programming #CleanCode #CodeNewbie #BuildInPublic #TechContent #DevelopersLife #UIEngineering

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories