DEV Community

Cover image for Setup React App With Redux Store
Prathamesh Patil
Prathamesh Patil

Posted on

Setup React App With Redux Store

Step 1: Create React App

npx create-react-app my-app

cd my-app

Step 2: Instal Redux , React Redux & Redux Thunk With Following CMD's

npm install redux

npm install react-redux

npm install redux-thunk

Step 3: Create reducers/reducer.js in src

Alt Text

Add Code as below in reducer.js:

const initialState = {
   name:prathamesh
}

function reducer(state = initialState, action) {
    switch (action.type) {
        case 'SET_CHECKED':
            return {
                ...state,
                name:action.payload.name
            }
            break;

        default:
            return state;
            break;
    }
}

export default reducer;
Enter fullscreen mode Exit fullscreen mode

Step 4: Time to connect store
Open src/index.js & import

import {Provider} from 'react-redux';
import {createStore,applyMiddleware, compose} from 'redux'
import reducer from './reducers/reducer'
import thunk from 'redux-thunk';
Enter fullscreen mode Exit fullscreen mode

Then make changes as below

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducer,composeEnhancers(
  applyMiddleware(thunk),
));

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

This will connect our store to app with react devtool.

Step 5:Connect any of the component to store

import React, { Component } from 'react'
import { connect } from 'react-redux'

class Check extends Component {

    render() {
        return (
            <div>
               <h1>{this.props.name}</h1>
            </div>
        )
    }
}

const mapStateToProps  = state => {
    return {
        isChecked : state.name
    }
}

export default connect(mapStateToProps,null)(Check);
Enter fullscreen mode Exit fullscreen mode

Above is a component named Check where we have connected store with connect function at the bottom which we have imported from react-redux & we can access the state by mapStateToProps.

Top comments (1)

Collapse
 
bazen profile image
Bazen

This is fine and well, but i suggest you checkout using redux hooks and thier redux-toolkit it will make your life as developer easier.