src/redux/store.js
where reducers are combined and the store is initializedsrc/redux/slices/
where reducers are implemented/src/redux/slices/
folder. Quick example:import { createSlice } from '@reduxjs/toolkit';
const initialState = {
products: []
};
const slice = createSlice({
name: 'products',
initialState,
reducers: {
setProducts(state, payload) {
state.products = [
{
id: '1',
slug: 'my-first-product',
title: 'My first product'
}
];
}
}
});
export const { reducer } = slice;
export default slice;
export function getProducts() {
return async dispatch => {
const response = await axios.get('/api/products');
dispatch(slice.actions.setProducts(response.data.products));
};
}
/src/redux/store.ts
file and add the new slice:import productsReducer from "./slices/products";
export const store = configureStore({
reducer: {
products: productsReducer,
},
});
import { useDispatch, useSelector } from 'react-redux';
import { getProducts } from '../redux/slices/products';
function ProductList() {
const dispatch = useDispatch();
const { products } = useSelector((state) => state.products);
useEffect(() => {
dispatch(getProducts());
}, [dispatch]);
return (
<div>
{products.map((product) => (
<div key={product.id}>
<div>{product.name}</div>
</div>
))}
</div>
);
}
createSlice
and createAsyncThunk
. Any time you click the "Increment" and "Decrement buttons in the example below, the following happens:<Counter>
component will see the new state value from the store and re-render itself with the new data