Home > front end >  Why i cant call a hook directly?
Why i cant call a hook directly?

Time:03-01

I'm learning to react and hooks, and I'm wondering why I can't call a hook directly. For example: In redux we have a hook called useDispatch() , but to use it I have to assign it to a const. For example:

const dispatch = useDispatch()

and then start using it by calling:

dispatch(someAction(state)).

Why is not possible call it directly like: useDispatch(someAction(state))?

CodePudding user response:

AFAIK there is nothing that stops you from calling and using hooks directly as long as you do it within the rules of hooks. Hooks should be called at the top level of application to avaid being called in different order between renders. It is explained pretty clear in offcial docs: https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level. When it comes to useDispatch() expample you provided, as it has been already metioned by @BenM, this hooks returns reference to dispatch function. I assume library authors decided to make it this way, so it can be reused and switch to hooks will require minimal code changes from library users. But if you wish, you can dispatch action just by calling hook this way:

useDispatch()(someAction(state))

CodePudding user response:

You're actually assigning the return value of useDispatch() to the constant dispatch in this instance, so dispatch() isn't an alias of useDispatch() (i.e. dispatch() and useDispatch() do different things).

Hooks often do more than just call a function (for instance useState()):

const [ count, setCount ] = useState(0);

Note that here, calls to useState() actually returns an array of the current value and the function to be called to update the state, so we assign its values using array destructuring.

  • Related