Redux is a popular state management library for JavaScript applications. Here are some examples to help you understand how to use Redux in different scenarios.
Basic Usage
To get started with Redux, you need to install the following packages:
redux
: The core Redux library.react-redux
: The official React integration with Redux.
npm install redux react-redux
Here's a simple example of a Redux application:
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
// Define the initial state
const initialState = {
count: 0
};
// Create a reducer
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 a Redux store
const store = createStore(counterReducer);
// Render the application
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
Action and Reducer
An action is a plain JavaScript object that describes what happened. A reducer is a function that takes the current state and an action, and returns the next state.
Here's an example of an action and a reducer:
// Action
const incrementAction = { type: 'INCREMENT' };
// Reducer
function counterReducer(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}
Middleware
Middleware allows you to extend Redux with custom functionality. One of the most popular middleware is Redux Thunk, which allows you to write action creators that return a function instead of an action.
Here's an example of using Redux Thunk:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
const store = createStore(counterReducer, applyMiddleware(thunk));
Async Actions
Async actions are actions that perform asynchronous operations, such as fetching data from an API.
Here's an example of an async action:
function fetchData() {
return dispatch => {
dispatch({ type: 'FETCH_DATA_REQUEST' });
fetch('/api/data')
.then(response => response.json())
.then(data => dispatch({ type: 'FETCH_DATA_SUCCESS', payload: data }))
.catch(error => dispatch({ type: 'FETCH_DATA_FAILURE', error }));
};
}
Links
For more information about Redux, please visit the following links: