Skip to content

Instantly share code, notes, and snippets.

@bengrunfeld
Last active July 29, 2020 08:05
Show Gist options
  • Save bengrunfeld/6fe1ce9eb39a6f6dffdcdcc307961167 to your computer and use it in GitHub Desktop.
Save bengrunfeld/6fe1ce9eb39a6f6dffdcdcc307961167 to your computer and use it in GitHub Desktop.
Example usage of useImperativeHandle
import { useState, useRef, forwardRef, useImperativeHandle } from "react";
const ChildOne = forwardRef((props, ref) => {
const [count, setCount] = useState(0);
useImperativeHandle(ref, () => ({
count,
}));
const updateCount = () => {
setCount((c) => c + 1);
console.log(count + 1);
};
return <button onClick={updateCount}>Increment</button>;
});
const ChildTwo = forwardRef((props, ref) => {
const checkCount = () => console.log("->", ref.current.count);
return <button onClick={checkCount}>Count</button>;
});
const Parent = () => {
const ref = useRef();
return (
<div>
<ChildOne ref={ref} />
<ChildTwo ref={ref} />
</div>
);
};
export default Parent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment