Riferimento rapido

Cheat Sheet Redux

Una guida rapida per Redux: creazione dello store, reducer puri, action creator, dispatch, middleware e hook di React Redux.

· Pubblicato

Redux e un contenitore di stato prevedibile per applicazioni JavaScript basato sul flusso dati unidirezionale.

Concetti Fondamentali e Creazione dello Store

import { createStore } from 'redux';

// Funzione reducer: funzione pura che calcola lo stato successivo
function counterReducer(state = { value: 0 }, action) {
  switch (action.type) {
    case 'counter/incremented':
      return { value: state.value + 1 };
    case 'counter/decremented':
      return { value: state.value - 1 };
    default:
      return state;
  }
}

// Crea lo store
const store = createStore(counterReducer);

// Sottoscrizione alle modifiche di stato
const unsubscribe = store.subscribe(() => {
  console.log('Stato corrente:', store.getState());
});

// Invia azioni
store.dispatch({ type: 'counter/incremented' }); // { value: 1 }
store.dispatch({ type: 'counter/decremented' }); // { value: 0 }

Action Creator e Middleware

// Action Creator
const incrementBy = (amount) => ({
  type: 'counter/incrementBy',
  payload: amount
});

// Pattern middleware (logging, thunk asincroni)
const loggerMiddleware = (storeAPI) => (next) => (action) => {
  console.log('Invio azione:', action);
  const result = next(action);
  console.log('Stato successivo:', storeAPI.getState());
  return result;
};

Hook React Redux (useSelector e useDispatch)

import React from 'react';
import { useSelector, useDispatch } from 'react-redux';

export function Counter() {
  const count = useSelector((state) => state.value);
  const dispatch = useDispatch();

  return (
    <div>
      <span>Count: {count}</span>
      <button onClick={() => dispatch({ type: 'counter/incremented' })}>
        +
      </button>
    </div>
  );
}

Redux Toolkit Moderno (RTK)

Le applicazioni Redux moderne utilizzano Redux Toolkit (createSlice, configureStore) per ridurre il codice boilerplate:

import { createSlice, configureStore } from '@reduxjs/toolkit';

const counterSlice = createSlice({
  name: 'counter',
  initialState: { value: 0 },
  reducers: {
    increment: (state) => { state.value += 1; },
    decrement: (state) => { state.value -= 1; }
  }
});

export const { increment, decrement } = counterSlice.actions;
export const store = configureStore({ reducer: counterSlice.reducer });

Riferimenti

Argomenti correlati