Skip to main content

My Typical Usage of Redux

Redux is a powerful tool for managing global state in JavaScript applications. In this post, I’ll share how I typically use Redux in my projects, with the help of Redux Toolkit to simplify the process.

Creating a Store

The first step in using Redux is creating a store. This is where your application’s global state lives.


import { configureStore } from "@reduxjs/toolkit";
import { rootReducer } from './reducer';

const store = configureStore({
reducer: rootReducer,
});

export { store };

Combining Reducers

Redux uses reducers to handle actions. A root reducer is often used to combine multiple reducers, each managing their own part of the state.


import { combineReducers } from "@reduxjs/toolkit";
import userSlice from "./userSlice";
import themeSlice from "./themeSlice";
import postSlice from './postSlice';

const rootReducer = combineReducers({
user: userSlice,
theme: themeSlice,
posts: postSlice
});

export { rootReducer };

Creating a Slice

A slice in Redux represents a portion of the state. Redux Toolkit’s createSlice function simplifies the process of creating reducers and actions.


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

const initialState = {
posts: {}
}

const postSlice = createSlice({
name: "post",
initialState,
reducers: {
getPosts(state, action) {
state.posts = action.payload;
},
}
});

export default postSlice.reducer;

export function SetPosts(post){
return (dispatch, getState) =>{
dispatch(postSlice.actions.getPosts(post));
}
}

Setting Up the Provider

To make the Redux store available to your React components, you need to use the Provider component from react-redux. Here’s how you can set it up:

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

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

Accessing and Using State

In a React component, you can access the state using the useSelector hook and dispatch actions using the useDispatch hook from react-redux.

In the example below, we’re dispatching the SetPosts action with a new post as the payload.

Here’s an example:

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

// Access state
const posts = useSelector(state => state.posts);

// Dispatch actions
const dispatch = useDispatch();
dispatch(SetPosts({id: 1, title: 'My first post'}));