Reputation: 525
I'm new in React hooks, in one of parts in our projects, we have a function to handle modal display in cards:
const toggleModal = () => setModalDisplay(!modalDisplay)
in this case, I have to pass this function to each child components... maybe for 10 or 1000 children!
So, regard to React JS DOC useCallback
returns a memoized function to reduce the memory usage and handle expensive computing. but I have to pass params to second argument to refresh callback and return the new one.
but in this case, we have a state to handle modal toggle, that every times has changes between true and false. so, with considering the logic of useCallback
and our use case, if I use useCallback
for this example, practically that function (toggleModal
) updates every times and useCallback
is useless for this use case.
for example:
const memoizedModalToggle = useCallback(
() => {
setModalDisplay(!modalDisplay)
},
[modalDisplay],
);
finally, is this a correct using of useCallback
? or I have mistake in implementation and logic?
Thanks
Upvotes: 0
Views: 527
Reputation: 404
ok, use useCallback when you want to avoid having to update a component or function when the state changes
example:
{useCallback(<TableStore
params={[JSON.stringify([selectedRoute]), data]}
tableName="custom_table"
method="Select"
>
<ReactTable
allowExport
onRowClick={onRowClick}
columns={columns}
allowSelection={false}
/>
</TableStore>, [selectedRoute, data])}
Here the table will change and update only when we click on the row or when our data has been updated.
in your case, not need to use useCallback
Upvotes: 0
Reputation: 160
I think you are confused between set the states and update callback functions in a memoized function with useCallback
For example, you can memoized your callback function with an empty array of dependencies:
const memoizedModalToggle = useCallback(
() => {
setModalDisplay(!modalDisplay)
},
[]
);
it will be something like useEffect
logic for callback functions.
Also you can use Set()
object to test this flow, because Set
is able to store unique functions by references and you are able to use set.size()
for checking the number of callbacks have generated.
Upvotes: 2