What is Redux and How can you apply it?
Table of contents
No headings in the article.
Redux is a JavaScript library for managing application state. It is often used with React to build user interfaces, but can also be used with other libraries or frameworks.
The basic principles of Redux are:
The entire application state is stored in a single JavaScript object, called the store.
The store can only be modified by dispatching actions, which are plain JavaScript objects that describe a change to the state.
The state changes are handled by pure functions called reducers, which take the current state and an action as arguments and return the next state.
To use Redux in a React application, you need to install the redux
and react-redux
libraries and configure them in your application.
Create a store by calling the
createStore
function from theredux
library, passing in a reducer function.Wrap your root component in a
<Provider>
component from thereact-redux
library, passing in the store as a prop.To access the state and dispatch actions from your component, you can use the
useSelector
anduseDispatch
hooks from thereact-redux
library.To update the state, you need to dispatch an action by calling the
dispatch
method on theuseDispatch
hook, passing in an action object.To handle the state update, you need to write a reducer function that takes the current state and an action as arguments and returns the next state.
Here's an example:
import { createStore } from 'redux';
import { Provider, useSelector, useDispatch } from 'react-redux';
// create a store
const store = createStore(reducer);
// root component
function App() {
const counter = useSelector(state => state.counter);
const dispatch = useDispatch();
return (
<div>
<h1>Counter: {counter}</h1>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
</div>
);
}
// wrap the root component in a provider
function Root() {
return (
<Provider store={store}>
<App />
</Provider>
);
}
// define the reducer function
function reducer(state, action) {
switch (action.type) {
case 'INCREMENT':
return { counter: state.counter + 1 };
default:
return state;
}
}