Steps in setting up react-redux app
create the react app by running npx create-react-app app_name
install the redux package module by running npm i react-redux
create a reducer
const countReducer = function (state = 0, action) {
switch (action.type) {
case "INCREMENT":
return state + 1;
case "DECREMENT":
return state - 1;
default:
return state;
}
};
create a redux store
import { createStore } from 'redux';
let store = createStore(countReducer);
Wrap the main app component with a provider
import { Provider } from 'react-redux';
const App = () => (
<Provider store={store}>
<h1>Helloworld PwC</h1>
</Provider>
);
Create and connect a container component
import { Provider, connect } from 'react-redux';
const Component = () => <h1>Helloworld </h1>;
const Container = connect()(Component);
const App = () => (
<Provider store={store}>
<Container />
</Provider>
);
Select and transform state from redux store
const mapStateToProps = state => {
return {
count: state
};
};
const Container = connect(mapStateToProps)(Component);
Use the state in the presentational component
const Component = ({count}) => <h1>Helloworld {count}</h1>;
Add buttons to the presentational components
const Component = ({count, handleIncrementClick, handleDecrementClick}) => (
<div>
<h1>Helloworld PwC {count}</h1>
<button onClick={handleDecrementClick}>Decrement</button>
<button onClick={handleIncrementClick}>Increment</button>
</div>
);
Pass Callback that dispatch action to store
const mapDispatchToProps = dispatch => {
return {
handleIncrementClick: () => dispatch({ type: 'INCREMENT' }),
handleDecrementClick: () => dispatch({type: 'DECREMENT'})
}
};
const Container = connect(mapStateToProps, mapDispatchToProps)(Component);
In conclusion, To set up redux for your react app, the above steps would come in handy.
Thanks and Happy Hacking!!!