Should I use redux in my application?
Actually, If you don’t want to use centralized state in store, then you can use props and state without redux.
Even Dan Abramov who made redux said that you need to use redux only when you need to.
Redux flow in React
Let's follow up step by step.
1. Make a Testcomponent
import React, { Component } from "react";
import { connect } from "react-redux";
import { Button } from "semantic-ui-react";
import { incrementCounter, decrementCounter } from "./testActions";
const mapState = state => ({
data: state.test.data
});
const actions = {
incrementCounter,
decrementCounter
};
class Testcomponent extends Component {
render() {
const { incrementCounter, decrementCounter, data} = this.props;
return (
<div>
<h1>Test component</h1>-
<h3> the answer is: {data}</h3>
<Button onClick={incrementCounter} color="green" content="Increment" />
<Button onClick={decrementCounter} color="red" content="Decrement" />
</div>
);
}
}
export default connect(
mapState,
actions
)(Testcomponent);
2. Make a TestActions
import { INCREMENT_COUNTER , DECREMENT_COUNTER } from './testConstants'
export const incrementCounter =() =>{
return {
type: INCREMENT_COUNTER
}
}
export const decrementCounter =()=>{
return{
type: DECREMENT_COUNTER
}
}
3. Make a Testconstants for actions and reducer
export const INCREMENT_COUNTER = "INCREMENT_COUNTER"
export const DECREMENT_COUNTER = "DECREMENT_COUNTER"
4. Make a reducer
import { createReducer } from '../../app/common/util/reducerUtil'
import { INCREMENT_COUNTER, DECREMENT_COUNTER } from "./testConstants";
const initialState = {
data: 142
};
const testReducer = (state = initialState, action) => {
switch (action.type) {
case INCREMENT_COUNTER:
return {...state, data: state.data + 1};
case DECREMENT_COUNTER:
return {...state, data: state.data - 1};
default:
return state;
}
};
export default createReducer(initialState, {
[INCREMENT_COUNTER]: incrementCounter,
[DECREMENT_COUNTER]: decrementCounter
});
And If you don’t want to use switch-case, then you can try this instead of using switch.
import { createReducer } from '../../app/common/util/reducerUtil'
import { INCREMENT_COUNTER, DECREMENT_COUNTER } from "./testConstants";
const initialState = {
data: 142
};
export const incrementCounter = (state, payload)=>{
return {...state, data: state.data + 1}
}
export const decrementCounter = (state, payload)=>{
return {...state, data: state.data -1 }
}
export default createReducer(initialState, {
[INCREMENT_COUNTER]: incrementCounter,
[DECREMENT_COUNTER]: decrementCounter
});
I used contents from Neil Cummings(who is teacher in Udemy)