Skip to content

Redux Hoja de referencia

Contenedor de estado predecible para aplicaciones JavaScript.

01

Primeros pasos

Reducer

Los reducers son funciones puras (state, action) => state.

redux
function counter(state = 0, action) {
  switch (action.type) {
    case "INCREMENT": return state + 1;
    case "DECREMENT": return state - 1;
    default: return state;
  }
}

Store

El store guarda el estado; usa dispatch para cambiarlo.

redux
import { createStore } from "redux";
const store = createStore(counter);

store.dispatch({ type: "INCREMENT" });
console.log(store.getState());

Redux Toolkit

Redux Toolkit simplifica Redux con createSlice.

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

const counter = createSlice({
  name: "counter",
  initialState: 0,
  reducers: {
    increment: s => s + 1,
    decrement: s => s - 1,
  }
});

const store = configureStore({ reducer: counter.reducer });
02

Integración con React

useSelector

Hooks para leer el estado y despachar acciones.

redux
import { useSelector, useDispatch } from "react-redux";

function Counter() {
  const count = useSelector(s => s);
  const dispatch = useDispatch();
  return <button onClick={() => dispatch({type: "INCREMENT"})}>{count}</button>;
}

Was this helpful?