Redux-Thunk is an add-on to the Redux library. Hosted as a separate package in NPM, it can be downloaded and set up as middleware when initializing Redux without complex configuration. It allows you to achieve asynchronous querying. Middleware in redux allows you to intercept a query and instead of making a single change on the stor it can make a series of queries, in the meantime they can query the API for external data. The whole thing is possible, obtainable without Redux-Thunk, but this one makes it much easier.

Proces, Redux-Thunk

An example query in Redux-Thunk

The simplest example of using Redux-Thunk would be to query the API to log in a user. For the query to run correctly, a couple of things need to happen.

  1. Setting the application state that the login has started.
  2. Sending the query to the API
  3. Setting the user data in the store
  4. Possibly returning an error

 

export const authLogin = (email, password) => {
  return dispatch => {
    dispatch(authStart());
    axios
      .post(`${API_URL}/auth/api/v1/login/`, {
        email: email,
        password: password
      })
      .then(res => {
        const token = res.data.token;
        const user = res.data.user;
        dispatch(authSuccess(token, user));
      })
      .catch(err => {
        dispatch(authFail(err));
      });
  };
};

 

With this approach, we can isolate some of the logic of our application to a single function. We can use data mocking from the API and fully test the performance of such a Thunk.

 

Are you looking for a contractor working with Redux-Thunk ?
logo

Alternatives to Redux-thunk

An alternative to Redux-thunk is the Context API, which is built directly into the React library. We can easily create asynchronous queries there. We will only see a practical difference when the Context API supports a sizable object where we will frequently update parameters. We may find that the Context API is then less efficient and runs DOM updates too often.

Although Redux is a separate library it has rich documentation with well-described examples. Examples for Redux-Thunk are also numerous and it is definitely a productive solution for maintaining application state.

Our offer

Web development

Find out more

Mobile development

Find out more

E-commerce

Find out more

UX/UI Design

Find out more

Outsourcing

Find out more

Related articles

Show all articles