Last active
July 29, 2020 08:05
-
-
Save bengrunfeld/6fe1ce9eb39a6f6dffdcdcc307961167 to your computer and use it in GitHub Desktop.
Example usage of useImperativeHandle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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