Skip to main content

Redux in React

Redux is a popular state management library that can be used with React to manage the application state more efficiently. In this tutorial, we'll learn how to set up Redux in a React app, create actions, reducers, and use the Redux store.

Installing Redux and React-Redux​

First, let's install the necessary packages:

npm install redux react-redux

Creating a Redux Store​

To create a Redux store, we need to define a reducer function and pass it to the createStore function from the redux package:

JavaScript
import { createStore } from 'redux';

function counterReducer(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}

const store = createStore(counterReducer);

export default store;

In this example, we've created a simple counter reducer that increments or decrements the state based on the dispatched action.

Creating a Redux Provider​

To make the Redux store available to our React components, we need to use the Provider component from the react-redux package:

JavaScript
import React from 'react';
import { Provider } from 'react-redux';
import store from './store';
import Counter from './Counter';

function App() {
return (
<Provider store={store}>
<Counter />
</Provider>
);
}

export default App;

Connecting Components to the Redux Store​

Now let's connect our Counter component to the Redux store using the useSelector and useDispatch hooks from the react-redux package:

JavaScript
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';

function Counter() {
const count = useSelector(state => state);
const dispatch = useDispatch();

return (
<div>
<h1>{count}</h1>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
<button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button>
</div>
);
}

export default Counter;

In this example, we've used the useSelector hook to access the current state value and the useDispatch hook to dispatch actions to the Redux store.

Conclusion​

In this tutorial, we've learned how to use Redux for state management in React applications. We've set up a Redux store, created actions and reducers, and connected our React components to the Redux store using the react-redux package.

By using Redux, you can maintain the state of your application in a more organized and efficient way, resulting in better performance and maintainability.