Refs forwarding is a technique for automatically passing Refs through a component to its children

Why refS forwarding

Some components need to manage their check state, focus, media playback, animation execution, and so on, and you need to handle the side effects of the child components in the parent component

Class component refs forwarding

You get the child component instance and instance method properties by passing the ref defined in the parent component to the child component

Refs forwarding of function components

Unlike class components, class components have instances from which instance methods can be retrieved, but function component property methods cannot be retrieved from the parent component.

If you’re a library developer and the user doesn’t know the library component class, what if the user wants to retrieve the library component from ref when the FunctionComponent class is FunctionComponent?

React also specifies the conditions for using ref:

forwardRef

The parent component passes in the parent component properties as a props object. The forwardRef passes in the ref property as the second parameter to the parent component

const ChildrenRef = React.forwardRef(Children)

function Children(props, ref) {}

function Parent(){
	const ref = useRef();

	return (
		<ChildrenRef ref={ref} />)}Copy the code

The basic principle is to avoid passing a REF directly to a subcomponent, because passing a ref directly in a class component means binding the entire subcomponent, but in a function component you cannot bind the entire subcomponent without an instance, so passing a REF would be ambiguous.

Do not use forwardRef

The child component DOM is bound by passing the ref defined in the parent to a child component property that is not ref name

function Children(props) {return <div ref={props.onRef}>123</div>}

function Parent(){
	const ref = useRef();

	return (
		<Children onRef={ref} />)}Copy the code

useImperativeHandle

Using useImperativeHandle, the parent component can retrieve method properties defined in the child component

This function takes three arguments: ref, callback, and deps

The ref () function binds the result of the callback function to the ref’s current property and updates the binding process based on the dependency

const inputRef = useRef();
useImperativeHandle(props.onRef, () = > ({
    onfocus: () = >{ inputRef.current.focus(); }}), []);Copy the code

The method attributes are essentially stored in ref because all operations on ref are on the same object.

Do not use useImperativeHandle

UseImperativeHandle is equivalent to the following implementation:

const inputRef = useRef();
useEffect(() = > {
    props.onRef.current = {
        onfocus: () = > {
            inputRef.current.focus();
        }
    }
}, [props.onRef])
Copy the code