Redux is a state management library for JavaScript applications. It helps you manage the application state easily and efficiently.
Redux includes the following objects you need to know:
Redux uses the Flux architecture, where the state of the application is stored in a single structure called store. Any changes to the state must go through dispatch to execute the action, and reducers are used to handle actions and update the state.
Here is a simple example of how to use Redux in a React application.
Installing Redux and React Redux:
npm install redux react-redux
Create the file actions.js to define actions:
// actions.js
export const increment = () => {
return {
type: 'INCREMENT',
};
};
export const decrement = () => {
return {
type: 'DECREMENT',
};
};
Create the file reducers.js to handle actions and update state:
// reducers.js
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;
}
};
export default counterReducer;
Create a file store.js to create a store and connect it to the React application:
// store.js
import { createStore } from 'redux';
import counterReducer from './reducers';
const store = createStore(counterReducer);
export default store;
Using Redux in React applications:
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from './actions';
function App() {
const count = useSelector((state) => state.count);
const dispatch = useDispatch();
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={() => dispatch(increment())}>Increment</button>
<button onClick={() => dispatch(decrement())}>Decrement</button>
</div>
);
}
export default App;
In the example above, we use the useSelector hook to get the state from the store and the useDispatch hook to send actions to the reducer. When the user clicks the "Increment" or "Decrement" button, the corresponding action will be sent to the reducer and the state will be updated.