<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Kiran D Patkar</title>
    <description>The latest articles on DEV Community by Kiran D Patkar (@kirandpatkar98).</description>
    <link>https://dev.to/kirandpatkar98</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F688192%2F15fc23b6-9424-403d-b1d5-3ec4b7601d0a.png</url>
      <title>DEV Community: Kiran D Patkar</title>
      <link>https://dev.to/kirandpatkar98</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/kirandpatkar98"/>
    <language>en</language>
    <item>
      <title>Experience the Power of Redux Toolkit</title>
      <dc:creator>Kiran D Patkar</dc:creator>
      <pubDate>Fri, 30 Dec 2022 15:46:35 +0000</pubDate>
      <link>https://dev.to/kirandpatkar98/learn-redux-toolkit-with-proper-setup-58l7</link>
      <guid>https://dev.to/kirandpatkar98/learn-redux-toolkit-with-proper-setup-58l7</guid>
      <description>&lt;h2&gt;
  
  
  Introduction:
&lt;/h2&gt;

&lt;p&gt;Redux Toolkit (RTK) is a set of utilities for Redux, a popular state management library for JavaScript applications. It provides a set of conventions and utilities that make it easier to build Redux applications by reducing the amount of boilerplate code you need to write. It structures our Redux code in a way that is easier to understand and maintain&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Why Redux Toolkit?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The problem with vanilla redux is it's having a lot of boilerplate code, which most of the developers don't want to do, we have to write action creators again and again in vanilla redux. Also, it requires more libraries to make it more effective&lt;br&gt;
Redux toolkit is a reincarnation of redux, it makes the developer's life so easy.&lt;/p&gt;

&lt;p&gt;The reason for preferring the Redux toolkit:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Less boilerplate code compared to vanilla redux&lt;/li&gt;
&lt;li&gt;No need to do extra setup for asynchronous operations,it has &lt;strong&gt;createAsyncThunk&lt;/strong&gt; which will take care of it&lt;/li&gt;
&lt;li&gt;It's easy to understand, we can achieve the same functionality that vanilla redux provides in a very short and sweet way.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Since 2019 Redux Toolkit is the officially recommended approach to write any Redux code.&lt;/strong&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Installation:
&lt;/h2&gt;

&lt;p&gt;We need  to install  two packages&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install @reduxjs/toolkit react-redux

       or

yarn add @reduxjs/toolkit react-redux
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For creating a new React based Project with a Redux toolkit pre-installed&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx create-react-app my-app --template redux
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Setup store
&lt;/h2&gt;

&lt;p&gt;In Redux, a store is an object that holds the application's state.&lt;br&gt;
It provides a way to access, update, and monitor the state. To create the store we have to import the &lt;strong&gt;configureStore&lt;/strong&gt; function from the Redux toolkit.&lt;/p&gt;

&lt;p&gt;Before configuring the store we have to create a redux reducer function that will specify how the state should be updated depending upon the actions triggered. Reducer function will take two arguments current state and action, it returns a new state depending upon the action.&lt;/p&gt;
&lt;h2&gt;
  
  
  Step 1: Implement createSilce method and export actions and reducer.
&lt;/h2&gt;

&lt;p&gt;In Redux, a slice is a piece of the application's state that is managed by a specific reducer. Redux Toolkit  provides the &lt;strong&gt;createSlice&lt;/strong&gt; utility for creating slices of state and the corresponding reducer and action creators. createSlice takes an object that specifies the initial state, reducer functions, and action creators for the slice.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createSlice } from '@reduxjs/toolkit';
const todoListSlice = createSlice({
    name: "todoList",
    initialState: [],
    reducers: {
        addTodo: (state, action) =&amp;gt; {
          state.push(action.payload);
    },
        removeTodo: (state, action) =&amp;gt; {
          state.filter(todo =&amp;gt; todo.id !== action.payload);
    }
    }
});
export const { addTodo, removeTodo } = todoListSlice.actions;
export default todoListSlice.reducer;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 2: Add Slice Reducers to the Store
&lt;/h2&gt;

&lt;p&gt;In Redux, the &lt;strong&gt;configureStore&lt;/strong&gt; function is a utility function provided by the redux-toolkit package that helps you set up a Redux store for your application. It takes a single argument, an options object, and returns a configured Redux store object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { configureStore } from '@reduxjs/toolkit';
import { combineReducers } from 'redux';
import todoList from 'todoListSlice';

const rootReducer = combineReducers({todoList}) which is similar to
const rootReducer = combineReducers({todoList:todoList})

If we want to use different attribute name then we can write like this
const example=combineReducers({attributeName:reducerName})

const store = configureStore({ devTools: true, reducer: rootReducer });
export default store;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have to pass a single reducer function to our store, as the app grows more complex, you'll want to split your reducing function into separate functions, each managing independent parts of the state.&lt;br&gt;
The &lt;strong&gt;combineReducers&lt;/strong&gt; helper function turns an object whose values are different reducing functions into a single reducing function.&lt;br&gt;
for ex: const rootReducer=combineReducers({reducer1,reducer2,....,reducer-N})&lt;/p&gt;

&lt;p&gt;The configureStore function accepts several options that allow you to customize the behavior of the store. Some common options include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;reducer: The root reducer of our application&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;devTools: This will allow us to inspect the state of our store&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;preloadedState: The initial state of the store.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Other than this there are many other options are vailable for configureStore. If you want more information about &lt;strong&gt;configureStore&lt;/strong&gt; you can read the documentation &lt;a href="https://redux-toolkit.js.org/api/configureStore"&gt;here&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Step 3: Connect our store to the app
&lt;/h2&gt;

&lt;p&gt;Now we need to connect our store to the app. This will make our app access the redux store that we have created.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Provider } from 'react-redux';
import store from './redux/store';
.....
 &amp;lt;Provider store={store}&amp;gt;
        &amp;lt;App /&amp;gt;
 &amp;lt;/Provider&amp;gt;
.....
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 4: Read and update the global state using useSelector() and useDispatch() hooks
&lt;/h2&gt;

&lt;p&gt;By using useSelector and useDispatch from react-redux, we can read the state from a Redux store and dispatch any action from a component, respectively.&lt;/p&gt;

&lt;h2&gt;
  
  
  useSelector():
&lt;/h2&gt;

&lt;p&gt;useSelector is a function that takes the current state as an argument and returns whatever data you want from it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useSelector } from 'react-redux';

const list = useSelector((state) =&amp;gt; state.todoList);

// Here todoList is the attribute name given to the reducer 


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  useDispatch():
&lt;/h2&gt;

&lt;p&gt;If we want to modify the global state we need to use useDispatch and the action that we already created in slice.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { addTodo } from 'todoListSlice';

export default const MyTodoList=()=&amp;gt; {
  const [text, setText] = useState('');
  // We will invoke useDispatch and store it to a variable
  const dispatch = useDispatch();

  const addTodo = (e) =&amp;gt; {
    e.preventDefault();
// Here we are updating the todoList state by making use of the action that we have created in todoList slice
    dispatch(addTodo(text));
    setText('');
  };

  return (
    &amp;lt;form onSubmit={addTodo}&amp;gt;
      &amp;lt;input
        type='text'
        value={text}
        onChange={(e) =&amp;gt; setText(e.target.value)}
      /&amp;gt;
      &amp;lt;button&amp;gt;Add todo&amp;lt;/button&amp;gt;
    &amp;lt;/form&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we want to remove the list from todoList we have to dispatch removeTodo action.&lt;/p&gt;

&lt;h2&gt;
  
  
  Handling asynchronous action in Redux toolkit
&lt;/h2&gt;

&lt;p&gt;To perform asynchronous logic before sending the processed result to the reducers we have to make use of &lt;strong&gt;createAsyncThunk&lt;/strong&gt; which is provided by toolkit&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createSlice } from '@reduxjs/toolkit'
  const asynchronousSlice = createSlice({
  name: 'async',
  initialState={
   isLoading:false,
   data:[],
   isSuccess:false,
   message:""
},
  reducers: {},
  extraReducers: {},
})

export default asynchronousSlice.reducer;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Within createSlice,synchronous requests are handled by reducer object and asynchronous requests are handled by extraReducer.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createAsyncThunk } from '@reduxjs/toolkit'
export const getData=createAsyncThunk("async/fetch",async(arg,thunkApi)=&amp;gt;{
const response=await fetch('url')
return response.data

})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will create an action with async/fetch. The action will also have three additional properties pending, fulfilled, and rejected, which can be used to track the status of the async action. Depending upon this we can show a loading screen in UI to make it more user friendly&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createSlice } from '@reduxjs/toolkit'
  const asynchronousSlice = createSlice({
  name: 'async',
  initialState={
   isLoading:false,
   data:[],
   isSuccess:false,
   message:""
},
  reducers: {},
  extraReducers: {

 [getData.pending]: (state) =&amp;gt; {
      state.isLoading = true
    },
 [getData.fulfilled]: (state, action) =&amp;gt; {
      state.isLoading = false
      state.data = action.payload
      state.isSuccess=true
    },
 [getData.rejected]: (state, action) =&amp;gt; {
      state.isLoading = false
      state.message = action.error
    }

},
})

export default asynchronousSlice.reducer;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's setup a component which will dispatch getData when it mounts.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getData } from 'asynchronousSlice'

export default function Home() {
  const dispatch = useDispatch()
  const { data, isLoading } = useSelector((state) =&amp;gt; state.async)

  useEffect(() =&amp;gt; {
    dispatch(getData())
  }, [])

  if (loading) return &amp;lt;p&amp;gt;Loading...&amp;lt;/p&amp;gt;

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h2&amp;gt;Details&amp;lt;/h2&amp;gt;
      {data.map((post) =&amp;gt; (
        &amp;lt;p key={post.id}&amp;gt;{post.title}&amp;lt;/p&amp;gt;
      ))}
    &amp;lt;/div&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion and Thoughts
&lt;/h2&gt;

&lt;p&gt;Redux Toolkit can be a useful tool for reducing the amount of code you have to write when working with Redux, and for helping you structure your code in a way that is easier to understand and maintain.&lt;/p&gt;

&lt;p&gt;Thanks for reading this article, and I hope you enjoyed reading it and learned something about Redux toolkit. Please leave a comment if you have any questions for me &lt;/p&gt;

</description>
      <category>redux</category>
      <category>react</category>
    </item>
  </channel>
</rss>
