As I understand, useImperativeHandle
helps parent component able to call function of its children component. You can see a simple example below
const Parent = () => { const ref = useRef(null); const onClick = () => ref.current.focus(); return <> <button onClick={onClick} /> <FancyInput ref={ref} /> </> } function FancyInput(props, ref) { const inputRef = useRef(); useImperativeHandle(ref, () => ({ focus: () => { inputRef.current.focus(); } })); return <input ref={inputRef} />; } FancyInput = forwardRef(FancyInput);
but it can be easy achieved by using only useRef
const Parent = () => { const ref = useRef({}); const onClick = () => ref.current.focus(); return <> <button onClick={onClick} /> <FancyInput ref={ref} /> </> } function FancyInput(props, ref) { const inputRef = useRef(); useEffect(() => { ref.current.focus = inputRef.current.focus }, []) return <input ref={inputRef} />; } FancyInput = forwardRef(FancyInput);
So what is the true goal of useImperativeHandle
. Can someone give me some advices?. Thank you
Thank you for another magnificent post. The place else may
anybody get that type of info in such a perfect
method of writing? I have a presentation next week,
and I’m at the look for such info.