Redux is a predictable state container for JavaScript apps. It helps manage the state of your application in a scalable way, especially in medium to large-scale applications where multiple components need to share and update the same state. When used with React.js, Redux can help manage the application's state more predictably and efficiently. In this guide, we’ll cover the basics of Redux and how to integrate it with React.js.
Redux is a state management library that provides a centralized store for all the components in your application. This store holds the entire state of the app, and the components subscribe to the store to get the updated state. Instead of passing props manually through every level of your application, Redux allows you to access the state in any component.
While React has its own built-in state management (using useState and useReducer), Redux is useful for more complex applications that involve:
Before we can start using Redux in our React project, we need to install a few dependencies:
You can install Redux and React-Redux using the following commands:
npm install redux react-redux
Or with Yarn:
yarn add redux react-redux
The Redux flow follows these four key steps:
Let's walk through a simple example to add Redux to a React app.
// store.js
import { createStore } from 'redux';
// Initial State
const initialState = {
count: 0,
};
// Reducer Function
function 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;
}
}
// Create Store
const store = createStore(counterReducer);
export default store;
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import App from './App';
import store from './store';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
// Counter.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
const Counter = () => {
const count = useSelector((state) => state.count); // Access state from Redux store
const dispatch = useDispatch(); // Dispatch actions to the store
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
<button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button>
</div>
);
};
export default Counter;
// App.js
import React from 'react';
import Counter from './Counter';
const App = () => {
return (
<div>
<h1>Redux Counter</h1>
<Counter />
</div>
);
};
export default App;
Now that the app is set up, it's time to run the React app to see Redux in action.
Run the following command to start the app:
npm start
You should now see a simple counter app. When you click the "Increment" and "Decrement" buttons, the count will change, and Redux will manage the state behind the scenes.
Congratulations! You've just implemented Redux in a basic React.js app. While this was a simple counter app, Redux becomes invaluable as your app grows in complexity. By managing state centrally, Redux makes your app more predictable, easier to debug, and more scalable.
Further Learning:
What is Redux?
Redux is a predictable state container for JavaScript apps. It helps you write applications that behave consistently across different environments (client, server, and native) and are easy to test.
How does Redux work?
Redux manages the state of your application by using a central store. Actions are dispatched to reducers, which update the store based on the action type. Components can subscribe to changes in the store and update the UI accordingly.
When should I use Redux?
Redux is useful for applications with a lot of complex state logic, especially when state needs to be shared across multiple components. If your app has global state management needs and components spread across various parts of the UI, Redux can help centralize and manage that complexity.
What are actions and reducers in Redux?
Actions are payloads of information that send data from your application to your Redux store. Reducers specify how the application's state changes in response to actions. They take the current state and an action as arguments and return a new state.
What are Redux middlewares?
Middleware allows you to extend Redux with custom functionality. Middleware is most commonly used for handling asynchronous actions in Redux, such as making API calls. Popular middleware includes Redux Thunk and Redux Saga.
Get in touch with us for expert solutions with the best team at
Ekanstech Solution.