Redux is a predictable state container for JavaScript applications, often used with React. Ever since I tried my hands on React, I was searching for a way to store component states in a centralized location. And when I found out that Redux is something which I have been searching for, I thought I should give it try. However, since I was mostly working on PHP projects, I was spending days just to get hold of basics of the Redux. I read tutorials and watched several videos. Ultimately it simply increases the haphazardness in my learning process. I was looking for a basic intro which can help even the novice to understand the Redux concept with ease.
After going through enormous hardship, I decided to make a simpler guide on Redux so that people can refer to my guide to learn about Redux in less than 5 minute. 🙂 Seriously, I am doing it in this blog.
Open a terminal and create a new React project. Use the following command.
npx create-react-app simplestredux
cd simplestredux
The first command creates a React app and the second one will take you inside root folder of the app. Below I am sharing the root directory structure of a typical React app for better understanding.
src/
|-- index.js
|-- App.js
|-- ...
For the sake of simplicity I will be editing only two files in this guide. The two files where we will make changes to make our simplest Redux example work are index.js and App.js inside the root directory.
Now install the necessary dependencies using the commands below:
npm install react redux react-redux
Let’s start editing the index.js first. Open index.js file in your react project. Import ‘Provider’ dependency from ‘react-redux’ and ‘createStore’ dependency from ‘react’. You can do that by pasting the below lines at the top part of your index.js file.
import { createStore } from 'redux';
import { Provider } from 'react-redux';
You are now ready to create a reducer function. Reducers are the pure functions that takes the current state of your app or a component in the app and an action as input and returns a new state based on the action. To create reducers use the following code block in your index.js after the last line where you have imported Provider module.
const initialState = {
count: 0,
};
const counterReducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT':
return { ...state, count: state.count + 1 };
case 'DECREMENT':
return { ...state, count: state.count - 1 };
default:
return state;
}
};
The next step is create a store in index.js. In order to that, paste the following code.
const store = createStore( counterReducer);
After this, we need to provide access to the Redux store to our React components. How can we do that? Just wrap our main component (often the root component) with the Provider
component from react-redux
. Simply change the code inside root.render() with the below code:
root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>,
</React.StrictMode>
);
With these we are done with editing index.js. Next, let change App.js where we will be adding new component too. Open your App.js file and let’s create a Redux store there. Import useSelector and useDispatch from ‘react-redux’ at the top part of the page.
import { useSelector, useDispatch } from 'react-redux';
Also add a Counter component. Bear with me on this. I am not using separate component folder for the sake of simplicity. The new component has two buttons to perform increment and decrement. There is also a label to display current counter value.
const Counter = () => {
const count = useSelector(state => state.count);
const dispatch = useDispatch();
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
<button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button>
</div>
);
};
Edit the App() function in App.js to look like the below code:
function App() {
return (
<div className="App">
<header className="App-header">
<Counter />
</header>
</div>
);
}
After making the above changes, we have accomplished the simplest Redux usage in our React app.
Run your project by running the below command:
npm start
You should be able to see your React project in a browser by visiting http://localhost:3000. I am sharing the screenshot below. You can play around by clicking either of the buttons to see state changes in your React app.
This is a the simplest Redux tutorial which I think most beginner React programmer will find handy. I am intentionally not following standard React guides like creating directories to properly organize stores, actions, components just to get the simplicity I want to achieve with my code. 🙂 I hope you find this interesting.