DEV Community

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

Posted on

3 2

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.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay