Skip to content

Instantly share code, notes, and snippets.

@AlexeyPogorelov
Last active February 17, 2021 11:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlexeyPogorelov/16cc647dd999e3b5efe34348e82da61d to your computer and use it in GitHub Desktop.
Save AlexeyPogorelov/16cc647dd999e3b5efe34348e82da61d to your computer and use it in GitHub Desktop.
useCallbacn in action
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