Last active
February 17, 2021 11:37
-
-
Save AlexeyPogorelov/16cc647dd999e3b5efe34348e82da61d to your computer and use it in GitHub Desktop.
useCallbacn in action
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 { useCallback, useRef } from "react"; | |
const Elem = ({ index, onClick }) => { | |
const onClickRef = useRef(onClick); | |
const handleEvent = useCallback(() => { | |
onClickRef.current(index); | |
}, [index, onClickRef]); | |
return <button onClick={handleEvent}>{index}</button>; | |
}; | |
export default function App() { | |
const handleClick = useCallback((index) => { | |
alert(index); | |
}, []); | |
return ( | |
<div className="App"> | |
{["1", "2", "3", "4", "5"].map((index) => ( | |
<Elem key={index} index={index} onClick={handleClick} /> | |
))} | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment