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
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;
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';
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')
);
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);
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)
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.