React useRef and forwardRef explained

one concept that often comes up is refs — especially useRef and forwardRef. Let’s understand them in a simple way 👇 🔹 useRef in React useRef is a React hook that allows us to persist values between renders without causing a re-render. It is commonly used to: Access DOM elements directly Store mutable values Maintain values between renders Example: import { useRef } from "react"; function InputFocus() { const inputRef = useRef(null); const handleFocus = () => { inputRef.current.focus(); }; return ( <> <input ref={inputRef} /> <button onClick={handleFocus}>Focus Input</button> </> ); } Here, useRef is used to directly access the input DOM element and focus it. 🔹 forwardRef in React Normally, refs cannot be passed to child functional components. forwardRef allows a parent component to pass a ref to a child component, giving access to the child’s DOM element. Example: import React, { forwardRef } from "react"; const CustomInput = forwardRef((props, ref) => { return <input ref={ref} {...props} />; }); export default CustomInput; Parent component: import { useRef } from "react"; import CustomInput from "./CustomInput"; function App() { const inputRef = useRef(); return ( <> <CustomInput ref={inputRef} /> <button onClick={() => inputRef.current.focus()}> Focus Child Input </button> </> ); } Here, the parent component can control the child input element using forwardRef. 🔹 Key Difference HookPurposeuseRefCreates a reference to store values or access DOMforwardRefAllows passing a ref from parent to child component 💡 Interview Tip: A common pattern is using forwardRef with useRef together so that parent components can interact with child DOM elements. 💬 Have you used forwardRef in real-world projects, like building reusable input or UI component libraries? #reactjs #frontenddevelopment #javascript #webdevelopment #reacthooks #interviewpreparation

To view or add a comment, sign in

Explore content categories