Skip to content

General Redux Hooks consumption

Mario Pérez edited this page Mar 13, 2023 · 2 revisions

Redux data is stored in a store. To access the store, we use the useSelect() and useDispatch() hooks to execute actions within the store. On the other hand, calls to the restAPI or consumption of external services use RTK Query, which offers other different hooks but which contain the same key functionality, the store.

React Redux Store Hooks

useSelector()

Allows you to extract data from the Redux store state, using a selector function

Official documentation

In this example we have a state with a counter field that stores a number. To access the value, we use the useSelector() hook with the corresponding function, accessing the state and displaying the attribute.

import { useSelector } from 'react-redux'

export const CounterComponent = () => {
  const counter = useSelector((state) => state.counter)
  return <div>{counter}</div>
}

useDispatch()

This hook returns a reference to the dispatch function from the Redux store.

Official documentation

Using the example above, we can add a button that executes the increment-counter action of the store reducer

import { useSelector } from 'react-redux'

export const CounterComponent = () => {
  const dispatch = useDispatch()
  const counter = useSelector((state) => state.counter)
  return (<>
      <button onClick={() => dispatch({ type: 'increment-counter' })}>
        Increment counter
      </button>
    <div>{counter}</div>
  </>)
}

RTK Query Hooks

Cuando Redux + RTKQuery genera los hooks sigue una convención de nombres: utiliza use??Query() para los queries y use??Mutation para las mutaciones.

Queries usage

Official documentation

  const { data, error, isLoading } = useExampleQuery('exampleParameter')

When we use a query, the hook exports three different fields:

  • isLoading: It is a boolean flag that indicates if the data is being loaded or if the requests associated with it have already been completed..
  • data: This field stores the data received by the API or the cached data.
  • error:If there has been an error in the query, it will be shown in this field.

The isLoading field does not indicate if the request has been successful or not, it only indicates if the requests have finished, so the data obtained when isLoading is false is not consistent if it is not checked that there are no errors in the error field

Mutations usage

Official documentation

const [trigger, result] = useExampleMutation()
var { isLoading: isUpdating } = result; // Object deconstruction

When using a mutation, the hooks exports a trigger and a complex object:

  • trigger: This function initializes the loading of data into the mutation. This function must be passed the parameters that are required in the mutation
  • result: Complex object that has multiple fields. We will use the isUpdating (in te example is renamed as isLoading) field to know if the request has been completed or not