javascript / expert
Snippet
Encapsulating Component APIs with useImperativeHandle
Instead of exposing the entire DOM node, useImperativeHandle allows you to define a custom, restricted API for a child component, improving encapsulation and maintainability.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const CustomInput = forwardRef((props, ref) => {const inputRef = useRef(null);useImperativeHandle(ref, () => ({focusAndSelect: () => {inputRef.current.focus();inputRef.current.select();},clear: () => {inputRef.current.value = '';}}));return <input ref={inputRef} {...props} />;});
react
Breakdown
1
forwardRef((props, ref) => { ... })
Wraps the component to allow it to receive a ref from its parent.
2
useImperativeHandle(ref, () => ({ ... }))
Customizes the instance value that is exposed to parent components when using ref.
3
inputRef.current.select()
Executes internal DOM logic that is abstracted away from the parent's concern.