Managing Refs and Layout in React
In this blog, we’ll explore hooks that help manage direct DOM manipulations, access mutable values, and control layout-related logic in React. Let’s look at useRef
, useImperativeHandle
, and useLayoutEffect
.
1. useRef
What is it? useRef
gives you a way to persist values across renders without triggering re-renders.
Real-Life Example: You can use useRef
to focus on an input field without causing a re-render.
import React, { useRef } from 'react';
function FocusInput() {
const inputRef = useRef(null);
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={() => inputRef.current.focus()}>Focus Input</button>
</div>
);
}
2. useImperativeHandle
What is it? useImperativeHandle
allows you to modify the instance values that are accessible by parent components using ref
.
Real-Life Example: You can use this to expose certain values or methods to parent components.
import React, { useImperativeHandle, useRef, forwardRef } from 'react';
const CustomInput = forwardRef((props, ref) => {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => inputRef.current.focus(),
}));
return <input ref={inputRef} type="text" />
});
function App() {
const inputRef = useRef();
return (
<div>
<CustomInput ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus Input from Parent</button>
</div>
);
}
3. useLayoutEffect
What is it? useLayoutEffect
works like useEffect
, but it fires synchronously after all DOM mutations.
Real-Life Example: This is useful when you need to measure DOM elements immediately after changes have been made.
import React, { useLayoutEffect, useRef, useState } from 'react';
function LayoutEffectExample() {
const divRef = useRef();
const [width, setWidth] = useState(0);
useLayoutEffect(() => {
setWidth(divRef.current.offsetWidth);
}, []);
return (
<div ref={divRef}>Width of this div: {width}px</div>
);
}
Now that we know about refs and layout, we’re ready for server-side hooks and custom hooks in the next blog!
Comments
Post a Comment