Redux


Introduction

Redux helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. Mira leverages Redux Toolkit, to keep the amount of boilerplate code and complexity to a minimum.

Usage

Mira contains the following folders/files to store any Redux related logic:
  • src/redux/store.js where reducers are combined and the store is initialized
  • src/redux/slices/ where reducers are implemented

1. Creating a new slice

If you want to create a new slice, pleae add a file to the /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));
  };
}

2. Add slice to root reducer

Open the /src/redux/store.ts file and add the new slice:
import productsReducer from "./slices/products";

export const store = configureStore({
  reducer: {
    products: productsReducer,
  },
});

3. Using the slice

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>
  );
}

Real-life example

The example below includes various methods, including createSlice and createAsyncThunk. Any time you click the "Increment" and "Decrement buttons in the example below, the following happens:
  • The corresponding Redux action will be dispatched to the store
  • The counter slice reducer will see the actions and update its state
  • The <Counter> component will see the new state value from the store and re-render itself with the new data
Example
0

Redux DevTools

Redux DevTools offers developer tools to power-up Redux development workflow or any other architecture which handles the state change (see integrations).
It can be used as a browser extension (for Chrome, Edge and Firefox), as a standalone app or as a React component integrated in the client app.