For enquiries call:

Phone

+1-469-442-0620

April flash sale-mobile

HomeBlogWeb DevelopmentRedux Toolkit: Usage Guide with Examples

Redux Toolkit: Usage Guide with Examples

Published
05th Sep, 2023
Views
view count loader
Read it in
8 Mins
In this article
    Redux Toolkit: Usage Guide with Examples

    The modern world applications depend not only on their user interface, but their state management is also necessary for them to perform appropriately. Redux is available in the market as a commonly used library to manage their state and has gained popularity due to its immense benefits to developers.

    Redux comes as a complete toolkit that will help you create complex logic easily. All thanks to its widespread libraries. Due to its increasing popularity, Redux is entering the top toolkits. You can go for a React JS online training to learn more about Redux. 

    Redux is a battery-included toolset getting more attention among React community and developers. Today, Redux and React are the top combos that help in managing the state of complex applications. Some say react redux toolkit is getting out of order due to its complexity of configuring with React and requiring bipolar plate code. But, despite this, companies are still using redux smoothly.  

    The Redux Tool Kit has options to configure the global store by abstracting the Redux API. It is advised to use the redux js toolkit only to develop fewer complex applications. So, in this article, we will discuss more Redux Toolkits for efficient Redux development. 

    What is Redux & How Does It Work?

    If you are a full-stack developer, you must have come across the redux toolkit react native and redux toolkit best practices. If not, then you must go for Web Development and Designing Course.  

    The Redux toolkit typescript hit the market in 2015 and has gained popularity as a popular state management library. If we see frameworks such as React, Angular, or Vue, each component manages its states internally.  

    While creating complex applications, managing the state among several components impacting the work is challenging. Therefore, Redux came into the picture to help developers to manage complex applications easily.  

    Redux has a centralized store to store all the states of the applications that are easily accessible by all the app components. Each component does not have to pass the props around within the component tree to access those states, as displayed below.

    Redux Component Tree
    Source: codecentric.de

    The Redux Flow 

    To work with Redux, you must understand its flow in detail. It includes simple steps that need attention.  

    • To trigger the updation of the state, a user must start interacting with the view. 
    • The view will dispatch a required action if you want to update a state. 
    • The action will reach the reducers and update the state in the store as per the action. 
    • A view is subscribed to the store that will listen about the change in any state. Then all changes will be notified using the subscription method that will reflect in the UI.

    Redux Flow
    Source: esri.com

    What is Redux Toolkit?

    Some people criticize Redux and its best practices as it adds a large amount of code that is sometimes considered unnecessary. Undoubtedly, it is considered the best product, especially for complex applications. Therefore, developers came up with the development of the Redux Toolkit (RTK), which has dramatically improved the efficiency of Redux development. 

    RTK eliminates the complexity and issues of the developers related to boilerplate and the addition of unwanted code. Simply said, it solves the following three major problems that developers had with Redux.  

    • It made it easier to configure Redux on any system.  
    • You will not require many libraries to get started with Redux and handle complex applications. 
    • With RTK, Redux can work with enough boilerplate code.  

    RTK APIs help developers to create small yet powerful Redux applications. Using React and RTK templates together, you can quickly bootstrap any application.  

    First, install React Redux- 

    Now create my-react-redux-app, as shown below.

    After the successful compilation of the app, you will see the below image.

    And directed to the localhost, as shown below. 

    Main Features of Redux Tool Kit API

    RTK APIs have several functions that help the Redux API function to exist. These functions help streamline the flow of the Redux rather than changing the flow. The different functions are- 

    1. cofigureStore

    It will create the instance of the Redux store by just accepting a named object to automatically set up the Redux DevTools extension. 

    2. createAction

    This function will accept the initial state's value and a lookup table of action types to perform better. It will then create an action for handling all the action types mentioned. 

    3. createReducer

    This function will accept the value of the initial state and a lookup table of the action types to create a reducer for handling all types of actions. 

    4. Createslice

    This function will accept the value of the initial state and a lookup table of reducer names and action creator function. 

    Actions are the object of JavaScript having type property. Not only this, but you can also include custom properties as per requirement. These properties describe what to do with the state but cannot change the state.  

    For example (react-redux toolkit example) 

    //add a todo item 
    const todoAppState = {
    todos: [
    { id: 0, text: 'Learn React', completed: true },
    { id: 1, text: 'Learn Redux', completed: false, color: 'purple' },
    { id: 2, text: 'Build something fun!', completed: false, color: 'blue' }
    ],
    filters: {
    status: 'Active',
    colors: ['red', 'blue']
    }
    } 

    The type is a string describing the action and the properties used to change the state. To dispatch an action, you must include the store.dispatch(action) method while the reducers will update the state. 

    While reducers are the functions that consider the current value of the state and then perform the required action mentioned in action to provide the new value to the state, reducers can change the state value. 

    For example- 

    //current state and action 
    //updates the value  
    function counterReducer(state = { value: 0 }, action) { 
    switch (action.type) { 
    case 'INCREASE': 
    return { value: state.value + 1 } 
    Case 'DECREASE': 
    return { value: state.value - 1 } 
    Default: 
    return state 
    } 
    } 

    Output: 

    Depends on the action. Action is 0,1,2. Depending on the value input. 

    Then the state will get updated in the store, which is now accessible by each app component, for creating a store using the following single line of code. 

    const store = createStore(myComponent); 

    You need to subscribe the components to the store so they can listen to the state updates to render it to the UI. You can use the store.subscribe() method for adding a change listener that will perform when the action is dispatched.

    Why Redux Toolkit?

    Now, you have understood the effectiveness of Redux as state management. It can easily predict the state and change it with proper functions. You can maintain and scale it quickly due to its standard practices. Not only this, Redux comes with several benefits such as testing, debugging, and improved performance. It is a high-level state management library that can easily integrate with top frameworks. 

    Some other benefits are: 

    • It will provide more code to optimize the state with the best practices. 
    • It reduces excessive boilerplate code and makes the code more manageable and cleaner. 
    • It will not require more packages to install to create scalable applications. 
    • It eliminates the need to write unnecessary reducers and actions and makes complex applications more accessible. 

    RTK Query

    RTK stands for Redux toolkit. It comes with a redux toolkit query add-on with the @reduxjs/toolkit package. It is designed to eliminate the use case of data fetching and caching, and others. It helps define the API interface for complex applications. It has made some tasks more accessible, such as loading data in a web application and eliminating the hand-written data fetching & caching logic. 

    Sometimes the basic knowledge of Redux and RTK is insufficient for using and implementing the RTK Query. You need to dive deeper into the additional global store management facility, where you will get additional information. Not only this, but you can also install the Redux DevTools browser extension to include all functionalities to traverse the cache behavior seamlessly. 

    Using the following two methods, you can use the RTK query within the application.  

    • import { createApi } from '@reduxjs/toolkit/query' 
    • /* automatically generates hooks regarding the defined endpoints */ 

    import { createApi } from '@reduxjs/toolkit/query/react' 

    How to Use Redux Toolkit in your project? [Step-by-Step]

    It requires some simple steps to be followed. 

    Step 1: how to install the redux toolkit

    You can install the redux toolkit React-Redux packages using the following command. 

    npm install @reduxjs/toolkit react-redux //redux toolkit npm 

    Or you can install it via Create React App and redux toolkit setup.

    npx create-react-app my-app --template redux

    Step 2: Creating and initializing the store to hold the state

    To create a store for storing the states, we will create a store.js file under the src folder, where you can add the following code. 

    import { configureStore } from '@reduxjs/toolkit' 
    export default configureStore({ 
    reducer: {} //add reducers here 
    }) 

    In the above code, the configureStore will replace the original createStore from Redux, create a store accepting the reducer functions as arguments, and set the Redux DevTools Extension for easy debugging. 

    Step 3: Provide a store in React app

    Now, you need every component in the React app to access this store. You can do this with the Provider's help from the react-redux package we have installed. 

    Below is the index.js file,  

    import store from './store' 
    import { Provider } from 'react-redux' 
    ReactDOM.render( 
    <Provider store={store}> 
    <App /> 
    </Provider>, 
    document.getElementById('root') 
    )  

    Step 4: Write Reducers and Actions

    It's time to write some reducer and action functions for the above-created Redux store. Earlier, reducers and actions are written separately.  

    Actions 

    // actions/index.js 
    export const Increase = () => ({ 
    type: 'INCREASE' 
    }) 
    export const Decrease = () => ({ 
    type: 'DECREASE' 
    }) 

    Reducers 

    // reducers/index.js 
    export default (state = 0, action) => { 
    switch (action.type) { 
    case 'INCREASE': 
    return state + 1 
    case 'DECREASE': 
    return state - 1 
    default: 
    return state 
    } 
    } 

    But with the Redux toolkit, you can create concise code using createSclice function. In the below counterSlice.js file, we are writing both the reducers and actions. 

    import { createSlice } from '@reduxjs/toolkit' //next js redux toolkit  
    export const counterSlice = createSlice({ 
    name: 'counter', 
    initialState: { 
    value: 0 
    }, 
    reducers: { 
    increase: state => { 
    state.value += 1 
    }, 
    decrease: state => { 
    state.value -= 1 
    } 
    } 
    }) 
    // case under reducers becomes an action 
    export const { increase, decrease } = counterSlice.actions 
    export default counterSlice.reducer 

    Combining reducers and actions will eliminate the need to switch among statements so you can efficiently manage the action with its corresponding reducer.  

    Step 5: Importing reducer

    Now, we will import the reducer into the store.js file to perform the actions on the states. Below is the code. 

    import { configureStore } from '@reduxjs/toolkit' //create react app redux toolkit  
    import counterReducer from '.counterSlice' //import our reducer from step 4 
    export default configureStore({ 
    reducer: { 
    counter: counterReducer //add our reducer from step 4 
    } 
    }) 

    Step 6: Adding the dispatch function in the UI

    We have already mentioned earlier in this article that the View triggers the actions that will dispatch to update the state. It is common to use the store.dispatch(action) to dispatch an action. But, today, we are using the React-Redux useDispatch hook for dispatching the required actions and useSelector for reading the store data. 

    Now, we will create the Counter.js file in our src folder that will specify the Counter component. We will import the useDispatch and useSelector hooks from React-Redux, as shown below. 

    import { useSelector, useDispatch } from 'react-redux' //create react app typescript redux toolkit  
    import { decrease, increase } from './counterSlice' 

    Now the counter will initialize two mentioned hooks and then return the UI elements as specified in the code using the dispatch(action).  

    export function Counter() { 
    const count = useSelector(state => state.counter.value) 
    // name property as 'counter.' 
    // initialState with a 'value' property 
    // useSelector to return the state.counter.value 
    const dispatch = useDispatch() 
    // dispatch function to dispatch our actions 
    return ( 
    <div> 
    <button onClick={() => dispatch(increase())}> 
    Increase 
    </button> 
    <p>{count}<p> 
    <button onClick={() => dispatch(decrease())}> 
    Decrease 
    </button> 
    </div> 
    ) 
    } 

    Bootstrapping React with Redux Toolkit

    One of the most significant limitations of the redux is the challenge required to integrate it with the existing application. But, with the Redux toolkit, you will get the option to bootstrap the React application. You can simply hit the following command on your terminal. 

    npx create-react-app my-redux-app --template redux 

    After the download, you can open the application in your choice of a text editor and check the critical file that makes the Redux store function.

    // store.js 
    import { configureStore } from '@reduxjs/toolkit' 
    import counterReducer from '../features/counter/counterSlice' 
     
    export const store = configureStore({ 
      reducer: { 
        counter: counterReducer, 
      }, 
      }) 

    The Redux store at app/store.js will be the central station for the Redux Toolkit application. 

    configureStore accepts a single configuration object with multiple parameters. The components can access the stored data after the Provider component from react-redux wraps the entire application. 

    // index.js 
    import React from 'react'; 
    import ReactDOM from 'react-dom'; 
    import './index.css'; 
    import App from './App'; 
    import { store } from './app/store'; 
    import { Provider } from 'react-redux'; 
    ReactDOM.render( 
    <React.StrictMode> 
    <Provider store={store}> 
    <App /> 
    </Provider> 
    </React.StrictMode>, 
    document.getElementById('root') 
    ); 

    Output: 

    React 18 ships the new root API ( ReactDOM.createRoot ) together with the legacy API (ReactDOM.render. 

    This code will not work as in the latest versions; ReactDom render is deprecated. 

    Please try a new function. 

    Redux Toolkit and the Ducks Pattern

    The structure of files does not impact how Redux will work. It is advised that developers group the files based on their shared features but not the file type.  

    As per the duck's pattern, it is highly recommended that you keep all the Redux functionalities in a single file. This file will export a reducer function by default, including all the actions, creators, and other data. Not only this, but if required, this file will also suggest the pattern for the action types. 

    RTK strongly follows the duck's pattern and combines all the reducers, actions, and constants in one file known as the slice.  

    // counterSlice.js 
    import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'; 
    import { fetchCount } from './counterAPI'; 
    const initialState = { 
    value: 0, 
    status: 'idle', 
    }; 
    // asynchronous function with createAsyncThunk 
    export const incrementAsync = createAsyncThunk( 
    'counter/fetchCount', 
    async (amount) => { 
    const response = await fetchCount(amount); 
    return response.data; 
    } 
    ); 
    // Redux Toolkit slice 
    export const counterSlice = createSlice({ 
    name: 'counter', 
    initialState, 
    reducers: { 
    increment: (state) => { 
    state.value += 1; 
    }, 
    decrement: (state) => { 
    state.value -= 1; 
    }, 
    incrementByAmount: (state, action) => { 
    state.value += action.payload; 
    }, 
    }, 
    // including actions generated by createAsyncThunk or in other slices. 
    extraReducers: (builder) => { 
    builder 
    .addCase(incrementAsync.pending, (state) => { 
    state.status = 'loading'; 
    }) 
    .addCase(incrementAsync.fulfilled, (state, action) => { 
    state.status = 'idle'; 
    state.value += action.payload; 
    }); 
    }, 
    }); 
    export const { increment, decrement, incrementByAmount } = counterSlice.actions; 
    // more code... 
    export default counterSlice.reducer; 

    Input 1 and the counter will increase, as shown above 

    The counterSlice file uses the createSlice method from RTK that will return an object along with the reducers and actions that can be used for injection with other middleware. 

    Unlock the Power of Python: Master the Art of Programming from Scratch. Start your coding journey today and discover the endless possibilities with Python. Join our comprehensive course now!

    Conclusion

    It is easy to set up a Redux and create a Redux application. With Redux, managing different states of complex applications has become more accessible. This article will highlight how to work around Redux along with simple terminologies. 

    If you are new to it, you can opt for KnowledgeHut’s React.js online training for a detailed process.

    Frequently Asked Questions (FAQs)

    1How do you implement a Redux toolkit?

    To implement redux toolkit, you would need to first install the redux toolkit and react-redux package, create a redux store, and call it your react app. You can check the docs here for further steps.

    2Is Redux toolkit easy?

    Redux toolkit is beginner friendly, and you do not necessarily need previous knowledge in regular redux to start out with it. Just get to understand how state management works, and you are good to go.

    3What is the difference between the Redux and Redux toolkit?

    While redux and redux toolkits essentially do the same thing, the redux toolkit provides APIs to manage common redux use cases. Redux toolkit also reduces the bulky boilerplate code that one usually has to work with when it comes to regular redux.

    4Does the Redux toolkit come with thunk?

    The Redux thunk package is already included by default in the redux toolkit.

    5What can I use instead of Redux?

    Instead of redux, you could prefer to use the redux toolkit, MobX, Flux, Apollo, vuex, and RxJS.

    Profile

    Njong Emy

    Blog Author

    Njong is a frontend web developer, constantly building her skills and aspiring to get better. Her hobbies include reading fiction, watching movies, and perusing Google, Stack Overflow, and Quora for even the tiniest tech-related queries. She also enjoys referring to herself in the third person, as that is definitely not weird at all.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon