useImperativeHandle — customize ref value.
1const FancyInput = React.forwardRef((props, ref) => {2 const inputRef = useRef();3 useImperativeHandle(ref, () => ({4 focus: () => inputRef.current.focus(),5 clear: () => { inputRef.current.value = ""; },6 getValue: () => inputRef.current.value,7 }));8 return <input ref={inputRef} {...props} />;9});1011// Usage12const ref = useRef();13ref.current.focus();14ref.current.clear();
Benefits: Encapsulate DOM access, clean API for parents, hide internal DOM details.
Use when: Wrapping third-party components, providing custom methods, abstracting DOM operations.