DEV Community

Sirima Insorn
Sirima Insorn

Posted on • Edited on

ReactJS with Redux Thunk

Installation and Setup

First, create a React project with create-react-app:

npx create-react-app react-with-redux-thunk
Enter fullscreen mode Exit fullscreen mode

If create-react-app version < 5.0.0:

npx create-react-app@latest react-with-redux-thunk
Enter fullscreen mode Exit fullscreen mode

Or

npx create-react-app@5.0.0 react-with-redux-thunk
Enter fullscreen mode Exit fullscreen mode

If you're using the basic Redux createStore API and need to set this up manually, first add the redux-thunk package:

yarn add redux-thunk react-redux redux redux-logger
Enter fullscreen mode Exit fullscreen mode

After installing, we need to combine reducer item into a rootReducer to create a single object in ./store/reducer.js file:

import { combineReducers } from "redux";

export const Reducers = combineReducers({
  // ...
});
Enter fullscreen mode Exit fullscreen mode

we need to enable redux thunk by use applyMiddleware() in ./store/index.js:

import { createStore, applyMiddleware } from "redux";
import thunkMiddleware from "redux-thunk";
import { createLogger } from "redux-logger";
import { Reducers } from "./reducer";

const loggerMiddleware = createLogger();
export const store = createStore(Reducers, applyMiddleware(thunkMiddleware, loggerMiddleware));
Enter fullscreen mode Exit fullscreen mode

Configure the provide it to your app

Now, include <Provider /> to ./src/index.js and pass the store as props

import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { store } from "./store";
import App from "./App";
import "./index.css";

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById("root")
);
Enter fullscreen mode Exit fullscreen mode

Go to [Part 2] How to use redux thunk

Top comments (0)