javascript / expert
Snippet
Fine-grained Control with useImperativeHandle
useImperativeHandle customizes the instance value that is exposed to parent components when using ref. Instead of exposing the entire DOM node, you can expose only specific methods, promoting better encapsulation and controlling how parents interact with child internals.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const CustomInput = React.forwardRef((props, ref) => {const inputRef = React.useRef();React.useImperativeHandle(ref, () => ({focus: () => inputRef.current.focus(),shake: () => {inputRef.current.classList.add('shake');setTimeout(() => inputRef.current.classList.remove('shake'), 500);}}));return <input ref={inputRef} {...props} />;});// Usage in Parentconst parentRef = React.useRef();<CustomInput ref={parentRef} /><button onClick={() => parentRef.current.shake()}>Alert!</button>
react
Breakdown
1
React.forwardRef((props, ref) => { ... })
Allows the component to receive a ref from its parent.
2
React.useImperativeHandle(ref, () => ({ ... }))
Defines the specific API (focus, shake) that the parent can access via the ref.