Expose React child component functions to parent component

Using React hooks to supply forwarded refs with child component functions

December 15, 2019
In category Development

Use hook useImperativeHandle to apply functions to the passed ref:

import React, { forwardRef, useState, useImperativeHandle } from "react";

export default forwardRef(function({ initValue = 0 }, ref) {
  const [counter, setCounter] = useState(initValue);

  useImperativeHandle(ref, () => ({
    addToCounter: value => setCounter(prevCounter => prevCounter + value)
  }));

  return (
    <div className="Counter">
      Counter: <span>{counter}</span>
    </div>
  );
});

Pass ref from parent to child component and then use exposed child component functions from the parent component:

function App() {
  const counterRef = useRef();

  function addCounter() {
    counterRef.current.addToCounter(1);
  }

  function decCounter() {
    counterRef.current.addToCounter(-1);
  }

  return (
    <div className="App">
      <Counter ref={counterRef} initialValue={0} />
      <button onClick={addCounter}>+</button>
      <button onClick={decCounter}>-</button>
    </div>
  );
}

This is just an example to showcase how to use useImperativeHandle with forwardRef to use functions that belong to other components.

As always, imperative code using refs should be avoided in most cases.

0 0

comments powered by Disqus