Using the Selector Hook

Another very important Hook that is provided by Redux is the Selector Hook. It allows us to get data from the Redux store state, by defining a selector function. The API for this Hook is as follows:

const result = useSelector(selectorFn, equalityFn)

selectorFn is a function that works similarly to the mapStateToProps function. It will get the full state object as its only argument. The selector function gets executed whenever the component renders, and whenever an action is dispatched (and the state is different than the previous state).

It is important to note that returning an object with multiple parts of the state from one Selector Hook will force a re-render every time an action is dispatched. If multiple values from the store need to be requested, we can do the following:

  • Use multiple Selector Hooks, each one returning a single field from the state object
  • Use reselect, or a similar library, to create a memoized selector (we are going to cover this in the next section)
  • Use the shallowEqual function from react-redux as equalityFn

We are now going to implement the Selector Hook in our ToDo application, specifically in the TodoList and TodoFilter components.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.134.78.106