A
A
Anastasia2021-01-20 16:49:43
React
Anastasia, 2021-01-20 16:49:43

React Hook useCallback - correct notation?

Help me understand the code:
1. If there are no dependencies, is it necessary to write an empty array or can I skip the second argument in useCallback, what's the difference?
2. If there is no argument, then why is the entry of the form _ => , and not the form ( ) => ?

const changeDragging = useCallback(val => setDragging(val), []);
const changeDraggingToTrue = useCallback(_ => changeDragging(true), [changeDragging]);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Pastukhov, 2021-01-20
@KnopkaNen

1) useCallback - this function memoizes callback according to dependencies in deps. So when you write an empty array in dependencies, you guarantee that changeDragging will always be the same function throughout the component's life cycle. And this is very important when you need to pass your changeDragging as props to the component below - because the same dependency. changeDraggingToTrue depends on changeDragging - so it's good practice to specify changeDragging as the deps of the second useCallback. But since changeDragging is already guaranteed immutability, you can not specify changeDragging as a dependency - nothing will change (= for the time being)
2) this is a matter of taste () => ... or _ => ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question