Showing posts with label Redux. Show all posts
Showing posts with label Redux. Show all posts

Dec 21, 2025

Redux Toolkit for React: Ditch Boilerplate and Build Your First Slice

Redux Toolkit is where Redux stops feeling “painful” and starts feeling fun. When Redux first clicked for me was the moment I deleted 50+ lines of boilerplate and replaced them with a tiny createSlice. In this part, you and I will move from “old-school Redux” to modern Redux Toolkit (RTK)—the version the official docs recommend for almost every new project now.


Why Redux Toolkit?


Classic Redux made you write:

  • Action type constants
  • Action creators
  • Big switch reducers
  • Manual immutability (return {...state, ...})
Redux Toolkit wraps all that into a few small helpers and encourages best practices by default:
  • configureStore → store setup + DevTools + middleware
  • createSlice → actions + reducer in one place
  • createAsyncThunk → async flows (we’ll use this in a later part)
If Redux ever felt “too much”, RTK is the cure.


Imagine a simple Redux slice as:


redux-slice


You focus on “what state changes” and RTK does the wiring.


Step 1: Install Redux Toolkit and React-Redux


If you haven’t already:


npm install @reduxjs/toolkit react-redux

This gives you everything needed for modern Redux in React.


Step 2: Create a Store with configureStore


Create a file: src/store.js


// src/store.js
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterSlice';

export const store = configureStore({
  reducer: {
    counter: counterReducer
  }
});

// Optional: you can log the initial state
console.log('Initial state:', store.getState());


What this does:

  • Combines all slices under reducer
  • Enables Redux DevTools automatically
  • Wires up sensible middleware (incl. for async later)
You’ll add more slices (e.g., user, todos) to this store as the app grows.


Step 3: Create Your First Slice with createSlice


Create: src/counterSlice.js


// src/counterSlice.js
import { createSlice } from '@reduxjs/toolkit';

const initialState = {
  value: 0,
  step: 1
};

const counterSlice = createSlice({
  name: 'counter',        // slice name
  initialState,
  reducers: {
    increment(state) {
      // Immer lets us "mutate" safely
      state.value += state.step;
    },
    decrement(state) {
      state.value -= state.step;
    },
    reset(state) {
      state.value = 0;
    },
    setStep(state, action) {
      state.step = action.payload;
    }
  }
});

export const { increment, decrement, reset, setStep } = counterSlice.actions;
export default counterSlice.reducer;


Key things to notice:

  • No manual switch statement.
  • No return { ...state }—you can write “mutating” code, and RTK handles immutability under the hood.
  • Action creators are generated for you (increment(), decrement(), etc.).
Mentally, you can picture this slice as a small box:

redux-slice1


Step 4: Wire Store to React with <Provider>


In src/index.js (or main.jsx):


import React from 'react';
import { createRoot } from 'react-dom/client';
import { Provider } from 'react-redux';
import { store } from './store';
import App from './App';

const root = createRoot(document.getElementById('root'));

root.render(
  <Provider store={store}>
    <App />
  </Provider>
);

Now every component inside <App /> can talk to the Redux store using hooks.


Step 5: Use Redux Toolkit in a React Component


Let’s build a nice little counter UI: src/App.js


// src/App.js
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement, reset, setStep } from './counterSlice';

function App() {
  const { value, step } = useSelector(state => state.counter);
  const dispatch = useDispatch();

  return (
    <div style={{ padding: '1rem', fontFamily: 'sans-serif' }}>
      <h1>Redux Toolkit Counter</h1>
      <p>Current value: {value}</p>

      <label>
        Step:
        <input
          type="number"
          value={step}
          onChange={e => dispatch(setStep(Number(e.target.value) || 1))}
          style={{ marginLeft: '0.5rem', width: '4rem' }}
        />
      </label>

      <div style={{ marginTop: '1rem' }}>
        <button onClick={() => dispatch(decrement())}>-</button>
        <button onClick={() => dispatch(reset())} style={{ margin: '0 0.5rem' }}>
          Reset
        </button>
        <button onClick={() => dispatch(increment())}>+</button>
      </div>
    </div>
  );
}
export default App;


How it flows conceptually:

User clicks "+" → dispatch(increment()) → counterSlice.reducer runs "increment" → state.counter.value changes → useSelector sees new state → React re-renders App with updated value


This is the same Redux flow, just with far less boilerplate.
You can visualize it as:

redux-full-flow

Why Redux Toolkit Is a Big Deal (Compared to Classic Redux)


In classic Redux, the same counter would require:

  • Constants: INCREMENT, DECREMENT, RESET
  • Action creators: increment(), decrement(), reset()
  • Reducer with switch and manual immutability
  • Manual root reducer + store setup

With RTK:
  • One slice file
  • One store file
  • Hooks in components

That’s it. It’s easier to teach, easier to test, and much cleaner to maintain.


What’s Next in the Series


In Part 3, we’ll go deeper into connecting multiple slices, structuring larger apps, and making sure your React components stay clean and maintainable as the Redux store grows.

We’ll also touch on:

  • Splitting Redux logic by feature (auth, todos, cart)
  • Using selectors for derived data
  • When to keep state in Redux vs local useState

Dec 20, 2025

Redux for Beginners: Store, Actions, Reducers Explained (React)

Remember when you had a simple React counter app with useState? Click button → count goes up. Perfect! Now imagine 10 components all needing that counter. Or a user profile that needs to sync across Header, Sidebar, and Profile pages. Suddenly, you're passing props 8 levels deep. That's "prop drilling hell"—and Redux was born to fix it.


I've been there. My first "serious" React app became a prop-passing nightmare. Redux felt intimidating at first, but once I got the three core pieces (Store, Actions, Reducers), everything clicked. Let's build your first store together—no prior knowledge needed!


The Problem Redux Solves (Real Example)


Without Redux (prop drilling mess):

App → Dashboard → Header → UserMenu → Profile → Settings → Notifications (8 props deep!)

With Redux (one global store):

Any component → dispatch action → store updates → any component reads fresh data


Visual flow:


redux-flow


Redux's Three Magic Pieces


1. Store = Your App's Single Source of Truth


Think of it as a giant JavaScript object holding all your app state:


{
  counter: 5,
  user: { name: 'Alice' },
  todos: [{ id: 1, text: 'Learn Redux' }]
}

2. Actions = "What happened?" Messages


Plain objects saying what changed:


{ type: 'counter/increment' }
// or
{ type: 'todos/addTodo', payload: { text: 'New task' } }


3. Reducers = "How does state change?" Rules


Pure functions that take current state + action → new state:


function counterReducer(state = 0, action) {
  switch(action.type) {
    case 'counter/increment':
      return state + 1;
    default:
      return state;
  }
}

Key rule: Reducers never mutate state—they always return new objects.



Your First Redux Store (Counter App)


Let's build a working counter. Create src/store.js:


// 1. Create store with initial state
import { createStore } from 'redux';

const initialState = { count: 0 };

function counterReducer(state = initialState, action) {
  switch(action.type) {
    case 'INCREMENT':
      return { ...state, count: state.count + 1 };
    case 'DECREMENT':
      return { ...state, count: state.count - 1 };
    case 'RESET':
      return initialState;
    default:
      return state;
  }
}

export const store = createStore(counterReducer);


Connect to React (src/index.js):


import React from 'react';
import { createRoot } from 'react-dom/client';
import { Provider } from 'react-redux';
import { store } from './store';
import App from './App';

const root = createRoot(document.getElementById('root'));
root.render(
  <Provider store={store}>
    <App />
  </Provider>
);


Use in component (src/App.js):


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

function App() {
  // Read from store
  const count = useSelector(state => state.count);
  
  // Send actions to store
  const dispatch = useDispatch();
  
  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
      <button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button>
      <button onClick={() => dispatch({ type: 'RESET' })}>Reset</button>
    </div>
  );
}

Boom! Working Redux counter. Open Redux DevTools—you'll see actions flowing and state updating live .


Redux vs useState/useReducer (Quick Comparison)


Feature
useState
Redux
Scope
Component only
App-wide
DevTools
None
Time travel!
Teams
Solo fine
Multiple devs
Async
Manual
Built-in patterns
Scale
<10 components
100+ components

When useState wins: Simple apps, 1-3 components sharing state.
When Redux wins: Medium+ apps, multiple devs, complex async flows.

Your First "Aha!" Moment


Before Redux: Pass count through 5 components. Change in Profile? Header doesn't know.
After Redux: Any component reads useSelector(state => state.count). Change anywhere? Everyone sees instantly.

That's the power—one store, many readers, predictable updates.

Next: Part 2 shows Redux Toolkit (90% less code!) + real todo CRUD. You'll never write vanilla Redux again.