Adding redux in React project (Refactor a simple project with Redux)
Consider a simple project, a counter application that works with two buttons, once for Increment and another for Decrement counter value.
In an actual scenario, we use the state for holding counter value like this:
in App.js:
import React, {Component} from 'react';
import CounterApp from './CounterApp'
class App extends Component {
render() {
return (
<CounterApp/>
);
}
}
export default App;
in CounterApp.js:
import React, {Component} from 'react';
class CounterApp extends Component {
state = {
counter: 0
};
handleIncrement = () => {
this.setState(prevState => ({
counter: prevState.counter + 1
}))
};
handleDecrement = () => {
this.setState(prevState => ({
counter: prevState.counter - 1
}))
};
render() {
return (
<div>
<button onClick={this.handleIncrement}>Increment</button>
<p>{this.state.counter}</p>
<button onClick={this.handleDecrement}>Decrement</button>
</div>
);
}
}
export default CounterApp;
A simple and basic example that implement with react class component and handled by two function handler (handleIncrement
and handleDecrement
)
And a state
with a value, counter
I'm using
prevState
because of it's a best practice when you forced to usethis.state.
insetState
!
Now, what would be this implementation with Redux?
First of all, you need to install redux and react-redux packages to your project via
npm
oryarn
.You can simply install them with one line of code:
or with yarn:
now back to project and create 3 files with these names:
action.js
,reducer.js
andstore.js
open
action.js
file. We should implement two actions for this app. One for increment and one for decrement.in action.js
so we should change reducer.js:
There are 3 main principles of using redux:
according to second principles, we must assume that the state is immutable, and each case(in switch) must return state individually. using ...state in the returned state means that if initialState will changing in future, these cases will work properly (in this example it's not necessary).
our functions in actions are pure(3rd principle)
and for last new file store.js:
now we should apply this store to our App component. so open App.js file and made these changes:
in App.js:
Provider wrapped the
CounterApp
component and will propagatestore
toApp
andCounterApp
and all other child components.finally, change the CounterApp.js:
we are using
increment
&decrement
actions to dispatch actions to redux.the
state
was removed and instead of state we create a special functionmapStateToProps' and use
connect` to connect the state to component props.That's done!