How can I memoize a callback generated in the map loop? This (obviously) gives an error:
const SomeComponent = ({ items }: { items: ItemData[] }) => {
const getItemCallback = (item: ItemData) => (e: React.MouseEvent) => {
e.preventDefault();
//do something with item
}
return <div>
{items.map(item => {
const callback = useCallback(getItemCallback(item));
return <Item title={item.title} itemCallback={callback} />
})}
</div>
}
3
Answers
Wrap
getItemCallback
inuseCallback
and pass it to the component:The component then calls the callback, and passes the
item
to create a new function wrapped withuseCallback
:The a updated version of your code using