?? React + Redux Toolkit: Managing State with Elegance

?? React + Redux Toolkit: Managing State with Elegance


Managing state in React can become a major challenge as your application scales. Traditional Redux helped structure global states better, but it had a lot of boilerplate code.

?? Redux Toolkit (RTK) simplifies and modernizes Redux by reducing complexity and improving performance.


?? What is Redux Toolkit (RTK)?

Redux Toolkit is the official Redux library that makes setting up the store, creating reducers, and handling actions much easier. It also improves performance by using Immer, which enables direct state updates while maintaining immutability.


?? Why Use Redux Toolkit?

? Less boilerplate – No more overly complex reducers and action creators

? Controlled mutability – Uses Immer to simplify state updates

? Better performance – Optimizes how state updates are handled

? Easy configuration – configureStore() includes best practices by default

? Powerful dev tools – Built-in support for Redux DevTools and middlewares like Thunk


?? How to Set Up Redux Toolkit in React?


1?? Install Redux Toolkit and React-Redux

npm install @reduxjs/toolkit react-redux        


2?? Create a State Slice

Instead of writing separate reducers, actions, and types, Redux Toolkit introduces Slices, which combine all these in a single structure.

Create a file counterSlice.js:

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

const initialState = {
  value: 0
};

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

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

?? Key Takeaways:

? createSlice() automatically generates reducers and actions, eliminating large switch case statements

? You can mutate state directly because Redux Toolkit uses Immer to ensure immutability under the hood


3?? Configure the Store

Now, set up the global store for your application.

Create a file store.js:

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

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

?? Key Takeaways:

? configureStore() automatically sets up Redux DevTools and useful middlewares

? Multiple reducers can be added easily


4?? Connect Redux to React

In index.js, wrap your application with <Provider> so components can access the global state:

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

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


5?? Use Redux Toolkit in a React Component

Now, let's use Redux Toolkit inside a React component.

Example in Counter.js:

import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement, incrementByAmount } from './counterSlice';

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

  return (
    <div>
      <h2>Counter: {count}</h2>
      <button onClick={() => dispatch(increment())}>+</button>
      <button onClick={() => dispatch(decrement())}>-</button>
      <button onClick={() => dispatch(incrementByAmount(5))}>+5</button>
    </div>
  );
};

export default Counter;        

?? Key Takeaways:

? useSelector() reads global state

? useDispatch() triggers actions to modify the state

? dispatch(incrementByAmount(5)) allows passing a payload to update the state


?? Conclusion

? Redux Toolkit significantly simplifies state management in React

? Reduces the verbosity of traditional Redux

? Ensures performance and best practices automatically

?? Have you used Redux Toolkit in your projects? What’s your experience with it? ??

#React #ReduxToolkit #StateManagement #WebDevelopment




Gabriel Demétrio Gauche

Full Stack Software Engineer | Front-end focused | ReactJS | React Native | NodeJS | AWS

2 周

Great content!

回复
Jardel Moraes

Data Engineer | Python | SQL | PySpark | Databricks | Azure Certified: 5x

3 周

Grateful for your perspective! ??

回复
Bruno Haick

Fullstack Engineer | Java | Spring Boot | Software Developer | React | Angular | Docker | PostgreSQL | MySQL | Linux | Google Cloud | AWS

4 周

nice post about redux toolkit Bruno Freitas

回复
Patrick Cunha

Lead Fullstack Engineer | Typescript Software Engineer | Nestjs | Nodejs | Reactjs | AWS

1 个月

Excellent overview of a modern solution to state management! The clear examples and key takeaways make it easy to understand and implement.

回复
Guilherme Luiz Maia Pinto

Back End Engineer | Software Engineer | TypeScript | NodeJS | ReactJS | AWS | MERN | GraphQL | Jenkins | Docker

1 个月

Thanks for sharing ??

回复

要查看或添加评论,请登录

Bruno Freitas的更多文章

社区洞察

其他会员也浏览了