<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Wali Muhammad on Medium]]></title>
        <description><![CDATA[Stories by Wali Muhammad on Medium]]></description>
        <link>https://medium.com/@wm4012388?source=rss-111c7c60297c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*pX40oGRbXoZ5N1Xu</url>
            <title>Stories by Wali Muhammad on Medium</title>
            <link>https://medium.com/@wm4012388?source=rss-111c7c60297c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 00:48:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wm4012388/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Redux Toolkit Query (RTK Query) — Complete Guide to Cache Management with Tags (tagTypes…]]></title>
            <link>https://medium.com/@wm4012388/redux-toolkit-query-rtk-query-complete-guide-to-cache-management-with-tags-tagtypes-521c9d34c3d7?source=rss-111c7c60297c------2</link>
            <guid isPermaLink="false">https://medium.com/p/521c9d34c3d7</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Wali Muhammad]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 13:38:02 GMT</pubDate>
            <atom:updated>2026-07-23T13:38:02.565Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MDzVdlrEI4qnRZQ-VMXu0w.png" /></figure><h3>Redux Toolkit Query (RTK Query) — Complete Guide to Cache Management with Tags (tagTypes, providesTags, invalidatesTags) Step by Step</h3><h3>Introduction</h3><p>In the previous articles, we learned how to configure <strong>Redux Toolkit Query (RTK Query)</strong>, fetch data using <strong>Queries</strong>, and create new data using <strong>Mutations</strong>. At this point, you can build applications that communicate with an API using GET and POST requests.</p><p>However, one important question still remains.</p><p>Imagine you have a page displaying a list of users.</p><p>When you add a new user successfully, what should happen?</p><p>Should the list automatically update?</p><p>Or should the user manually refresh the page?</p><p>Similarly, suppose you update a user’s information or delete a product from an inventory. Should your application still display the old cached data?</p><p>Of course not.</p><p>The UI should always display the latest information from the server.</p><p>This is where <strong>RTK Query Tags</strong> become one of the framework’s most powerful features.</p><p>Tags allow RTK Query to understand <strong>which cached data has become outdated</strong> and automatically refetch fresh data when necessary.</p><p>Without Tags, developers often write manual refetch logic, dispatch additional actions, or reload pages after every mutation. RTK Query eliminates this boilerplate by providing a clean and automatic cache invalidation system.</p><p>In this article, you’ll learn everything about:</p><ul><li>What caching is</li><li>Why caching exists</li><li>Why stale data becomes a problem</li><li>What Tags are</li><li>tagTypes</li><li>providesTags</li><li>invalidatesTags</li><li>Automatic refetching</li><li>Cache invalidation</li><li>Cache lifetime</li><li>Refetch options</li><li>Best practices used in production applications</li></ul><p>Every concept is explained step by step with practical examples.</p><h3>Understanding Caching</h3><p>Before learning Tags, you first need to understand <strong>Caching</strong>.</p><p>Imagine your application fetches all users.</p><pre>GET /users</pre><p>The server responds with:</p><pre>[<br>  {<br>    &quot;id&quot;: 1,<br>    &quot;name&quot;: &quot;Ali&quot;<br>  },<br>  {<br>    &quot;id&quot;: 2,<br>    &quot;name&quot;: &quot;Ahmed&quot;<br>  }<br>]</pre><p>Instead of requesting this data every time the component renders, RTK Query stores it in memory.</p><p>This stored copy is called the <strong>Cache</strong>.</p><p>The next time another component requests the same endpoint, RTK Query simply returns the cached data instead of making another network request.</p><p>Benefits include:</p><ul><li>Faster applications</li><li>Reduced API requests</li><li>Better performance</li><li>Improved user experience</li><li>Less server load</li></ul><p>Caching is one of the biggest reasons RTK Query performs so well.</p><h3>The Problem with Caching</h3><p>Although caching is beneficial, it introduces another challenge.</p><p>Suppose the cached data contains:</p><pre>Ali<br>Ahmed</pre><p>Now another user adds:</p><pre>John</pre><p>to the database.</p><p>Your cache still contains only:</p><pre>Ali<br>Ahmed</pre><p>Your application is now displaying outdated information.</p><p>This is called <strong>Stale Cache</strong>.</p><p>RTK Query needs a way to know that the cached data is no longer valid.</p><p>That’s exactly what Tags solve.</p><h3>What Are Tags?</h3><p>A Tag is simply a label attached to cached data.</p><p>Think of it as a name that identifies a particular cache.</p><p>Example:</p><pre>Users</pre><p>or</p><pre>Products</pre><p>or</p><pre>Posts</pre><p>Whenever data changes, RTK Query checks which Tag is affected.</p><p>If the Tag becomes invalid, RTK Query automatically refetches the latest data from the server.</p><p>No manual refresh required.</p><h3>How Tags Work</h3><p>The complete process looks like this:</p><pre>GET Users<br>      │<br>      ▼<br>Cache Users<br>      │<br>      ▼<br>Tag = Users<br>      │<br>      ▼<br>POST User<br>      │<br>      ▼<br>Invalidate Users Tag<br>      │<br>      ▼<br>Automatic Refetch<br>      │<br>      ▼<br>Updated UI</pre><p>This entire workflow happens automatically.</p><h3>Step 1 — Define tagTypes</h3><p>Inside your API Slice:</p><pre>export const api = createApi({</pre><pre>  reducerPath: &quot;api&quot;,</pre><pre>  baseQuery: fetchBaseQuery({<br>    baseUrl: &quot;...&quot;,<br>  }),</pre><pre>  tagTypes: [&quot;Users&quot;],</pre><pre>  endpoints: (builder) =&gt; ({<br>  }),</pre><pre>});</pre><h3>Understanding tagTypes</h3><pre>tagTypes: [&quot;Users&quot;],</pre><p>Before RTK Query can use Tags, we must tell it which Tags exist.</p><p>Here we define one Tag named:</p><pre>Users</pre><p>You can define multiple Tags.</p><p>Example:</p><pre>tagTypes: [<br>  &quot;Users&quot;,<br>  &quot;Posts&quot;,<br>  &quot;Products&quot;,<br>  &quot;Orders&quot;,<br>]</pre><p>Think of tagTypes as registering categories of cache that your application manages.</p><h3>Step 2 — providesTags</h3><p>Now create a GET endpoint.</p><pre>getUsers: builder.query({</pre><pre>  query: () =&gt; &quot;users&quot;,</pre><pre>  providesTags: [&quot;Users&quot;],</pre><pre>}),</pre><h3>What Does providesTags Mean?</h3><p>Whenever this Query runs successfully, RTK Query stores its response inside the cache.</p><p>This line:</p><pre>providesTags: [&quot;Users&quot;]</pre><p>attaches the <strong>Users Tag</strong> to that cached response.</p><p>Think of it as saying:</p><blockquote><em>“This cached data belongs to the Users category.”</em></blockquote><p>Now RTK Query knows exactly which cache this query created.</p><h3>Step 3 — invalidatesTags</h3><p>Now let’s create a Mutation.</p><pre>addUser: builder.mutation({</pre><pre>  query: (newUser) =&gt; ({</pre><pre>    url: &quot;users&quot;,</pre><pre>    method: &quot;POST&quot;,</pre><pre>    body: newUser,</pre><pre>  }),</pre><pre>  invalidatesTags: [&quot;Users&quot;],</pre><pre>}),</pre><h3>What Does invalidatesTags Mean?</h3><p>Suppose a user creates a new record.</p><p>The database changes.</p><p>Our cached Users list is now outdated.</p><p>This line:</p><pre>invalidatesTags: [&quot;Users&quot;]</pre><p>tells RTK Query:</p><blockquote><em>“The Users cache is no longer valid.”</em></blockquote><p>Immediately after the Mutation succeeds, RTK Query automatically performs:</p><pre>GET /users</pre><p>again.</p><p>Your UI updates automatically.</p><p>No refresh button.</p><p>No manual dispatch.</p><p>No additional API call inside React.</p><p>Everything happens automatically.</p><h3>Complete Example</h3><pre>export const api = createApi({</pre><pre>  reducerPath: &quot;api&quot;,</pre><pre>  baseQuery: fetchBaseQuery({<br>    baseUrl: &quot;https://jsonplaceholder.typicode.com/&quot;,<br>  }),</pre><pre>  tagTypes: [&quot;Users&quot;],</pre><pre>  endpoints: (builder) =&gt; ({</pre><pre>    getUsers: builder.query({</pre><pre>      query: () =&gt; &quot;users&quot;,</pre><pre>      providesTags: [&quot;Users&quot;],</pre><pre>    }),</pre><pre>    addUser: builder.mutation({</pre><pre>      query: (user) =&gt; ({<br>        url: &quot;users&quot;,<br>        method: &quot;POST&quot;,<br>        body: user,<br>      }),</pre><pre>      invalidatesTags: [&quot;Users&quot;],</pre><pre>    }),</pre><pre>  }),</pre><pre>});</pre><p>This is the most common pattern you’ll use in production applications.</p><h3>What Happens Internally?</h3><p>Imagine this sequence.</p><pre>App Starts<br>      │<br>      ▼<br>GET Users<br>      │<br>      ▼<br>Cache Created<br>      │<br>      ▼<br>Tag Attached<br>      │<br>      ▼<br>User Adds New User<br>      │<br>      ▼<br>Mutation Success<br>      │<br>      ▼<br>Users Tag Invalidated<br>      │<br>      ▼<br>Automatic Refetch<br>      │<br>      ▼<br>Cache Updated<br>      │<br>      ▼<br>React Re-renders</pre><p>This predictable cycle keeps your UI synchronized with the server.</p><h3>Dynamic Tags</h3><p>Large applications often cache individual records.</p><p>Instead of:</p><pre>providesTags: [&quot;Users&quot;]</pre><p>you can provide Tags dynamically.</p><p>Example:</p><pre>providesTags: (result) =&gt;</pre><pre>  result<br>    ? [<br>        ...result.map(({ id }) =&gt; ({<br>          type: &quot;Users&quot;,<br>          id,<br>        })),<br>        { type: &quot;Users&quot;, id: &quot;LIST&quot; },<br>      ]<br>    : [{ type: &quot;Users&quot;, id: &quot;LIST&quot; }]</pre><p>Now each user has its own Tag.</p><p>Example:</p><pre>Users-1</pre><pre>Users-2</pre><pre>Users-3</pre><p>This allows RTK Query to refresh only one user instead of refetching the entire list.</p><p>This technique is commonly used in enterprise applications.</p><h3>Cache Lifetime</h3><p>RTK Query doesn’t keep cached data forever.</p><p>By default:</p><pre>60 Seconds</pre><p>After the last component stops using the query, RTK Query waits <strong>60 seconds</strong> before removing it from memory.</p><p>You can customize this.</p><p>Example:</p><pre>keepUnusedDataFor: 120</pre><p>Now cached data stays for:</p><pre>120 Seconds</pre><p>Longer cache lifetimes reduce unnecessary API requests but may increase memory usage.</p><p>Choose a value that matches your application’s needs.</p><h3>Refetch Options</h3><p>Sometimes you want RTK Query to refetch data under specific conditions.</p><h3>Refetch on Mount</h3><pre>useGetUsersQuery(undefined, {</pre><pre>  refetchOnMountOrArgChange: true,</pre><pre>});</pre><p>Whenever the component mounts again, RTK Query fetches fresh data instead of relying solely on the cache.</p><h3>Refetch on Window Focus</h3><pre>refetchOnFocus: true</pre><p>Imagine the user switches to another browser tab.</p><p>While they are away, another user updates the data.</p><p>When the original user returns, RTK Query automatically refetches the latest information.</p><h3>Refetch on Reconnect</h3><pre>refetchOnReconnect: true</pre><p>Suppose the internet connection disappears.</p><p>When the connection returns, RTK Query automatically requests fresh data.</p><p>No manual retry logic required.</p><h3>When Should You Use Tags?</h3><p>Tags are especially useful whenever data changes.</p><p>Examples include:</p><ul><li>User Management</li><li>Product Management</li><li>Shopping Cart</li><li>Orders</li><li>Blog Posts</li><li>Comments</li><li>Notifications</li><li>Inventory Systems</li></ul><p>If your application performs Create, Update, or Delete operations, you should almost always use Tags.</p><h3>Common Beginner Mistakes</h3><p>Many beginners encounter the same issues when first working with RTK Query Tags. Here are the most common ones:</p><ul><li>Forgetting to define tagTypes in createApi().</li><li>Using invalidatesTags without a matching providesTags.</li><li>Misspelling Tag names (for example, &quot;User&quot; vs &quot;Users&quot;). Tag names are case-sensitive and must match exactly.</li><li>Expecting a query to refetch automatically without invalidating the relevant Tag.</li><li>Invalidating every Tag in the application when only one resource changed, leading to unnecessary network requests.</li><li>Forgetting that mutations don’t automatically update cached queries unless you configure cache invalidation or update the cache manually.</li></ul><p>Checking these points first can save a lot of debugging time.</p><h3>Best Practices</h3><p>As your application grows, using Tags consistently becomes increasingly important. Here are some best practices followed in production applications:</p><ul><li>Define all your tagTypes at the top of your API Slice to keep them centralized.</li><li>Use plural, descriptive names such as &quot;Users&quot;, &quot;Posts&quot;, and &quot;Products&quot; for list resources.</li><li>For large datasets, prefer <strong>dynamic Tags</strong> with IDs so that only the affected item is refreshed instead of refetching the entire collection.</li><li>Use invalidatesTags only for resources that actually changed.</li><li>Combine Tags with keepUnusedDataFor and refetch options to balance freshness and performance.</li><li>Organize related endpoints within a single API Slice so they can share Tags effectively.</li></ul><p>Following these practices will keep your API layer efficient, predictable, and easier to maintain.</p><h3>Key Takeaways</h3><p>Let’s summarize the most important concepts from this article:</p><ul><li><strong>Caching</strong> stores API responses so they can be reused without making unnecessary network requests.</li><li>Cached data can become <strong>stale</strong> when the underlying data changes on the server.</li><li><strong>Tags</strong> act as labels that identify cached data.</li><li><strong>tagTypes</strong> registers the types of Tags your API Slice can use.</li><li><strong>providesTags</strong> attaches Tags to cached query results.</li><li><strong>invalidatesTags</strong> marks those Tags as outdated after a mutation.</li><li>Once a Tag is invalidated, RTK Query automatically refetches any active queries associated with that Tag.</li><li>Features such as <strong>dynamic Tags</strong>, <strong>cache lifetime</strong>, and <strong>automatic refetch options</strong> give you fine-grained control over how and when data stays up to date.</li></ul><p>Understanding Tags is one of the biggest milestones in learning RTK Query because it allows you to build applications that stay synchronized with the backend automatically, without writing extra state management logic.</p><h3>What’s Next?</h3><p>Now that you understand how RTK Query manages caching and automatic updates, the next step is to learn how to build a <strong>complete CRUD application</strong> using all of these concepts together.</p><p>In the next article, we’ll create a production-style project that includes:</p><ul><li>Fetching records with <strong>Queries</strong></li><li>Creating records with <strong>Mutations</strong></li><li>Updating records using <strong>PUT</strong> and <strong>PATCH</strong></li><li>Deleting records with <strong>DELETE</strong></li><li>Dynamic route parameters</li><li>Optimistic updates</li><li>Cache invalidation using Tags</li><li>Error handling and loading states</li><li>Folder organization and project best practices</li></ul><p>By the end of the next guide, you’ll understand how all the pieces of RTK Query fit together in a real-world React application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=521c9d34c3d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redux Toolkit Query (RTK Query) — Complete Guide to POST Data (Create Data) with Step-by-Step Code…]]></title>
            <link>https://medium.com/@wm4012388/redux-toolkit-query-rtk-query-complete-guide-to-post-data-create-data-with-step-by-step-code-721ea827c21d?source=rss-111c7c60297c------2</link>
            <guid isPermaLink="false">https://medium.com/p/721ea827c21d</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Wali Muhammad]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 11:40:36 GMT</pubDate>
            <atom:updated>2026-07-23T13:40:53.771Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ABffgULJlcc4_RaYrdrjVQ.png" /></figure><h3>Redux Toolkit Query (RTK Query) — Complete Guide to POST Data (Create Data) with Step-by-Step Code Explanation</h3><h3>Introduction</h3><p>In the previous article, we learned how to configure <strong>Redux Toolkit Query (RTK Query)</strong> and perform <strong>GET requests</strong> using builder.query(). We fetched data from an API and displayed it in a React application without writing useEffect(), useState(), or manual API logic.</p><p>However, fetching data is only one part of working with APIs. Real-world applications also need to <strong>create</strong>, <strong>update</strong>, and <strong>delete</strong> data.</p><p>For example:</p><ul><li>A registration page sends new user information to the server.</li><li>A login page sends credentials for authentication.</li><li>A blog application creates new posts.</li><li>An e-commerce website creates new orders.</li><li>A task management application adds new tasks.</li></ul><p>All of these operations involve sending data <strong>from the frontend to the backend</strong>, which is typically done using an <strong>HTTP POST request</strong>.</p><p>In RTK Query, POST requests are handled using <strong>Mutations</strong>, not Queries.</p><p>In this article, we’ll learn how to send data to a server using <strong>builder.mutation()</strong>. Every line of code, every function, and every configuration option will be explained in detail so you understand not only <strong>how</strong> it works, but also <strong>why</strong> it works.</p><h3>Understanding HTTP Methods</h3><p>Before writing any code, it’s important to understand why we use different HTTP methods.</p><p>A REST API usually supports several request types:</p><p>MethodPurposeExampleGETRetrieve dataGet all usersPOSTCreate new dataAdd a new userPUTReplace existing dataReplace a userPATCHUpdate part of existing dataUpdate user nameDELETERemove dataDelete a user</p><p>In this article, our focus is <strong>POST</strong>, which is used to create new resources on the server.</p><h3>Why Doesn’t POST Use builder.query()?</h3><p>Many beginners ask this question.</p><p>If builder.query() fetches data, why can&#39;t it also send data?</p><p>The answer lies in their purpose.</p><h3>Queries</h3><p>Queries are designed for <strong>reading data</strong>.</p><p>Examples include:</p><ul><li>Get Users</li><li>Get Products</li><li>Get Orders</li><li>Get Posts</li></ul><p>Queries automatically cache responses because the same data may be requested multiple times.</p><h3>Mutations</h3><p>Mutations are designed for <strong>changing data</strong>.</p><p>Examples include:</p><ul><li>Create User</li><li>Update User</li><li>Delete User</li><li>Login</li><li>Register</li></ul><p>Mutations tell the server that something has changed.</p><p>Because of this, RTK Query treats them differently from queries.</p><h3>What We Are Going to Build</h3><p>We’ll create a simple form that sends a new user to the server.</p><p>The API endpoint will be:</p><pre>https://jsonplaceholder.typicode.com/users</pre><p>The request body will look like this:</p><pre>{<br>  &quot;name&quot;: &quot;John Doe&quot;,<br>  &quot;email&quot;: &quot;john@example.com&quot;<br>}</pre><h3>Project Structure</h3><pre>src<br>│<br>├── app<br>│   └── store.js<br>│<br>├── services<br>│   └── api.js<br>│<br>├── components<br>│   └── AddUser.jsx<br>│<br>├── App.jsx<br>│<br>└── main.jsx</pre><p>Our Redux Store setup remains the same. We only need to add a <strong>Mutation Endpoint</strong> and create a component that submits data.</p><h3>Step 1 — Create a Mutation Endpoint</h3><p>Open:</p><pre>src/services/api.js</pre><p>Add the following endpoint inside the endpoints section.</p><pre>import { createApi, fetchBaseQuery } from &quot;@reduxjs/toolkit/query/react&quot;;</pre><pre>export const api = createApi({<br>  reducerPath: &quot;api&quot;,</pre><pre>  baseQuery: fetchBaseQuery({<br>    baseUrl: &quot;https://jsonplaceholder.typicode.com/&quot;,<br>  }),</pre><pre>  endpoints: (builder) =&gt; ({</pre><pre>    addUser: builder.mutation({</pre><pre>      query: (newUser) =&gt; ({<br>        url: &quot;users&quot;,<br>        method: &quot;POST&quot;,<br>        body: newUser,<br>      }),</pre><pre>    }),</pre><pre>  }),</pre><pre>});</pre><pre>export const {<br>  useAddUserMutation,<br>} = api;</pre><p>Let’s understand every line.</p><h3>Understanding builder.mutation()</h3><pre>addUser: builder.mutation({</pre><p>Unlike builder.query(), which retrieves data, builder.mutation() is used whenever we want to modify server data.</p><p>Typical use cases include:</p><ul><li>Creating users</li><li>Registering accounts</li><li>Logging in</li><li>Updating products</li><li>Deleting posts</li></ul><p>Whenever your application changes backend data, use a Mutation.</p><h3>Understanding query()</h3><pre>query: (newUser) =&gt; ({</pre><p>The function receives whatever data we pass from React.</p><p>Suppose we dispatch:</p><pre>addUser({<br>  name: &quot;John&quot;,<br>  email: &quot;john@example.com&quot;,<br>});</pre><p>The parameter:</p><pre>newUser</pre><p>contains:</p><pre>{<br>  name: &quot;John&quot;,<br>  email: &quot;john@example.com&quot;<br>}</pre><p>This object becomes the request body.</p><h3>Understanding URL</h3><pre>url: &quot;users&quot;,</pre><p>Since our base URL is:</p><pre>https://jsonplaceholder.typicode.com/</pre><p>RTK Query automatically creates:</p><pre>https://jsonplaceholder.typicode.com/users</pre><p>No need to repeat the entire URL.</p><h3>Understanding Method</h3><pre>method: &quot;POST&quot;,</pre><p>This tells RTK Query to send a POST request.</p><p>Without specifying the method, the request defaults to GET.</p><h3>Understanding Body</h3><pre>body: newUser,</pre><p>Everything inside newUser is sent to the server.</p><p>Example request:</p><pre>{<br>  &quot;name&quot;: &quot;John&quot;,<br>  &quot;email&quot;: &quot;john@example.com&quot;<br>}</pre><p>The server receives this object exactly as it appears.</p><h3>Step 2 — Export the Generated Hook</h3><pre>export const {<br>  useAddUserMutation,<br>} = api;</pre><p>Just like Queries automatically generated:</p><pre>useGetUsersQuery()</pre><p>Mutations automatically generate:</p><pre>useAddUserMutation()</pre><p>We didn’t write this Hook manually.</p><p>RTK Query generated it for us.</p><h3>Step 3 — Create the React Component</h3><p>Create:</p><pre>src/components/AddUser.jsx</pre><p>Add the following code.</p><pre>import { useState } from &quot;react&quot;;</pre><pre>import { useAddUserMutation } from &quot;../services/api&quot;;</pre><pre>const AddUser = () =&gt; {</pre><pre>  const [name, setName] = useState(&quot;&quot;);<br>  const [email, setEmail] = useState(&quot;&quot;);</pre><pre>  const [<br>    addUser,<br>    {<br>      isLoading,<br>      isSuccess,<br>      error,<br>    },<br>  ] = useAddUserMutation();</pre><pre>  const handleSubmit = async (e) =&gt; {</pre><pre>    e.preventDefault();</pre><pre>    await addUser({<br>      name,<br>      email,<br>    });</pre><pre>    setName(&quot;&quot;);<br>    setEmail(&quot;&quot;);</pre><pre>  };</pre><pre>  return (<br>    &lt;form onSubmit={handleSubmit}&gt;</pre><pre>      &lt;input<br>        type=&quot;text&quot;<br>        placeholder=&quot;Enter Name&quot;<br>        value={name}<br>        onChange={(e) =&gt; setName(e.target.value)}<br>      /&gt;</pre><pre>      &lt;input<br>        type=&quot;email&quot;<br>        placeholder=&quot;Enter Email&quot;<br>        value={email}<br>        onChange={(e) =&gt; setEmail(e.target.value)}<br>      /&gt;</pre><pre>      &lt;button type=&quot;submit&quot;&gt;<br>        Add User<br>      &lt;/button&gt;</pre><pre>      {isLoading &amp;&amp; &lt;p&gt;Saving...&lt;/p&gt;}</pre><pre>      {isSuccess &amp;&amp; &lt;p&gt;User Added Successfully.&lt;/p&gt;}</pre><pre>      {error &amp;&amp; &lt;p&gt;Something went wrong.&lt;/p&gt;}</pre><pre>    &lt;/form&gt;<br>  );</pre><pre>};</pre><pre>export default AddUser;</pre><p>Now let’s understand everything.</p><h3>Understanding useAddUserMutation()</h3><pre>const [<br>  addUser,<br>  {<br>    isLoading,<br>    isSuccess,<br>    error,<br>  },<br>] = useAddUserMutation();</pre><p>Unlike Queries, Mutation Hooks return <strong>an array</strong>, not an object.</p><p>The first item:</p><pre>addUser</pre><p>is the function that sends the request.</p><p>The second item contains useful information about the request.</p><h3>Understanding addUser()</h3><pre>await addUser({<br>  name,<br>  email,<br>});</pre><p>This sends the following request:</p><pre>POST /users</pre><p>with this JSON body:</p><pre>{<br>  &quot;name&quot;: &quot;John&quot;,<br>  &quot;email&quot;: &quot;john@example.com&quot;<br>}</pre><p>The server receives this object and creates a new user.</p><h3>Understanding Mutation States</h3><p>RTK Query automatically provides several useful states.</p><h3>isLoading</h3><pre>isLoading</pre><p>Becomes true while the request is being sent.</p><p>Useful for disabling buttons or showing loaders.</p><h3>isSuccess</h3><pre>isSuccess</pre><p>Becomes true after the request succeeds.</p><p>Useful for displaying success messages or redirecting users.</p><h3>error</h3><pre>error</pre><p>Contains server errors if something goes wrong.</p><p>Useful for displaying friendly error messages.</p><h3>Step 4 — Render the Component</h3><p>Open:</p><pre>src/App.jsx</pre><p>Replace everything with:</p><pre>import AddUser from &quot;./components/AddUser&quot;;</pre><pre>function App() {<br>  return &lt;AddUser /&gt;;<br>}</pre><pre>export default App;</pre><p>Now run the project.</p><pre>npm run dev</pre><p>Fill out the form and click <strong>Add User</strong>.</p><p>RTK Query sends the POST request automatically.</p><h3>Complete Request Flow</h3><p>Here’s what happens behind the scenes.</p><pre>User Fills Form<br>        │<br>        ▼<br>Clicks Submit<br>        │<br>        ▼<br>addUser()<br>        │<br>        ▼<br>Generated Mutation Hook<br>        │<br>        ▼<br>RTK Query<br>        │<br>        ▼<br>fetchBaseQuery()<br>        │<br>        ▼<br>POST Request<br>        │<br>        ▼<br>Server Response<br>        │<br>        ▼<br>Mutation State Updates<br>        │<br>        ▼<br>React Re-renders</pre><p>Notice how we never wrote:</p><ul><li>fetch()</li><li>axios.post()</li><li>useEffect()</li><li>Manual loading state</li><li>Manual error state</li></ul><p>RTK Query handled all of that for us.</p><h3>builder.query() vs builder.mutation()</h3><p>Understanding the difference between these two methods is essential.</p><p>Featurebuilder.query()builder.mutation()PurposeFetch dataModify dataTypical HTTP MethodsGETPOST, PUT, PATCH, DELETEGenerates HookuseGetUsersQuery()useAddUserMutation()Automatic Fetch on RenderYesNoTriggered ManuallyNoYesCommon Use CasesReading dataCreating, updating, deleting data</p><p>Choosing the correct one keeps your API layer predictable and easy to understand.</p><h3>Best Practices</h3><p>When working with POST requests in RTK Query, keep these recommendations in mind:</p><ul><li>Use builder.mutation() for any operation that changes server data.</li><li>Keep request payloads small and send only the fields the API expects.</li><li>Always handle isLoading, isSuccess, and error to improve the user experience.</li><li>Give endpoints descriptive names such as addUser, createPost, or registerUser.</li><li>Validate form input before sending data to the server.</li><li>Consider using unwrap() if you want to handle success and errors with try...catch in your components.</li></ul><h3>Key Takeaways</h3><p>By completing this guide, you’ve learned how to:</p><ul><li>Create a Mutation using builder.mutation().</li><li>Configure a POST endpoint inside an API Slice.</li><li>Send JSON data to a backend server.</li><li>Use the automatically generated useAddUserMutation() Hook.</li><li>Trigger a POST request from a React form.</li><li>Handle loading, success, and error states without writing boilerplate.</li><li>Understand the difference between Queries and Mutations.</li><li>Follow best practices for creating clean, maintainable API interactions.</li></ul><p>This pattern is used in real-world applications for user registration, authentication, creating blog posts, submitting orders, and many other forms of data creation.</p><h3>What’s Next?</h3><p>Now that you’ve learned how to create data with POST requests, the next step is to update and remove existing data.</p><p>In the next article, we’ll explore:</p><ul><li>Updating data using <strong>PUT</strong> and <strong>PATCH</strong> requests.</li><li>Deleting records using <strong>DELETE</strong> requests.</li><li>Passing dynamic IDs to mutation endpoints.</li><li>Invalidating cache so UI updates automatically.</li><li>Using <strong>Tags (</strong><strong>providesTags and </strong><strong>invalidatesTags)</strong> to keep data synchronized without manually refetching.</li></ul><p>By the end of the next guide, you’ll be able to build a complete CRUD application with RTK Query using production-ready patterns.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=721ea827c21d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redux Toolkit Query (RTK Query) — The Complete Beginner’s Guide to Setting Up RTK Query in a React…]]></title>
            <link>https://medium.com/@wm4012388/redux-toolkit-query-rtk-query-the-complete-beginners-guide-to-setting-up-rtk-query-in-a-react-281575953aa7?source=rss-111c7c60297c------2</link>
            <guid isPermaLink="false">https://medium.com/p/281575953aa7</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[js]]></category>
            <dc:creator><![CDATA[Wali Muhammad]]></dc:creator>
            <pubDate>Tue, 21 Jul 2026 09:42:05 GMT</pubDate>
            <atom:updated>2026-07-21T09:42:05.994Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V97gIotHhn0wQu5lJe9IHA.png" /></figure><h3>Redux Toolkit Query (RTK Query) — The Complete Beginner’s Guide to Setting Up RTK Query in a React Project</h3><h3>Introduction</h3><p>When building modern React applications, one of the most common tasks is communicating with a backend API. Whether you’re creating an e-commerce website, a banking dashboard, a social media application, or an admin panel, your frontend constantly needs to send requests to a server to fetch, create, update, or delete data.</p><p>Many developers initially use the <strong>Fetch API</strong> or libraries like <strong>Axios</strong> to perform these requests. While both approaches work well for small projects, they become difficult to manage as applications grow. You often find yourself writing repetitive code for loading states, error handling, caching, refetching, request cancellation, and state management.</p><p>Imagine you have ten different pages in your application, and each page makes multiple API requests. Soon, you’ll have dozens of useEffect() hooks, many useState() variables, duplicate API logic, and inconsistent error handling scattered throughout your project. Maintaining this code becomes increasingly difficult.</p><p>To solve these problems, the Redux team introduced <strong>Redux Toolkit Query (RTK Query)</strong>.</p><p>RTK Query is a powerful data-fetching and caching solution built directly into Redux Toolkit. It automatically handles many of the repetitive tasks involved in working with APIs, allowing you to focus on building features instead of writing boilerplate code.</p><p>In this comprehensive guide, you’ll learn everything you need to know to set up RTK Query in a React application from scratch. Every step is explained in detail so that even if you’ve never used RTK Query before, you’ll understand not only <strong>how</strong> to implement it but also <strong>why</strong> each step is necessary.</p><h3>What is RTK Query?</h3><p>RTK Query is a data fetching and caching tool that is included as part of Redux Toolkit.</p><p>Its primary purpose is to simplify communication between your React application and your backend APIs.</p><p>Instead of manually writing API functions, managing loading states, storing server responses inside Redux, handling errors, caching responses, and updating UI components, RTK Query automates these responsibilities.</p><p>You simply define your API endpoints, and RTK Query generates React Hooks for you automatically.</p><p>This means significantly less code and a much cleaner project structure.</p><h3>Why Was RTK Query Introduced?</h3><p>Before RTK Query, developers typically used Axios or Fetch API together with Redux.</p><p>The process usually looked like this:</p><pre>React Component<br>       │<br>       ▼<br>Dispatch Async Action<br>       │<br>       ▼<br>Axios / Fetch API<br>       │<br>       ▼<br>Receive Response<br>       │<br>       ▼<br>Store Response in Redux<br>       │<br>       ▼<br>Handle Loading State<br>       │<br>       ▼<br>Handle Error State<br>       │<br>       ▼<br>Update UI</pre><p>Although this approach works, it requires writing a lot of repetitive code.</p><p>For every API request, developers usually need to:</p><ul><li>Create async functions</li><li>Create loading state</li><li>Create error state</li><li>Store data manually</li><li>Update Redux state manually</li><li>Handle caching manually</li><li>Refetch data manually</li></ul><p>RTK Query removes almost all of this boilerplate.</p><h3>Why Should You Use RTK Query?</h3><p>RTK Query provides many built-in features that simplify API management.</p><p>Some of the most important benefits include:</p><ul><li>Automatic API caching</li><li>Automatic loading states</li><li>Automatic error handling</li><li>Automatic request deduplication</li><li>Automatic data refetching</li><li>Generated React Hooks</li><li>Optimized performance</li><li>Easy integration with Redux Toolkit</li></ul><p>Instead of worrying about API state management, you simply focus on displaying data.</p><h3>How RTK Query Works</h3><p>Understanding the overall workflow will make the setup much easier.</p><pre>React Component<br>       │<br>       ▼<br>Generated Hook<br>(useGetUsersQuery)<br>       │<br>       ▼<br>RTK Query<br>       │<br>       ▼<br>Backend API<br>       │<br>       ▼<br>Receives Response<br>       │<br>       ▼<br>Caches Data<br>       │<br>       ▼<br>Returns Data to React</pre><p>Notice that React never communicates directly with the backend.</p><p>Everything passes through RTK Query.</p><p>This allows RTK Query to cache responses, prevent duplicate requests, and automatically update your UI.</p><h3>Prerequisites</h3><p>Before setting up RTK Query, make sure your project already has:</p><ul><li>React</li><li>Redux Toolkit</li><li>React Redux</li></ul><p>If you’ve followed the previous articles in this series, your project is already prepared.</p><h3>Installing Required Packages</h3><p>If Redux Toolkit isn’t already installed, run:</p><pre>npm install @reduxjs/toolkit react-redux</pre><p>Let’s understand each package.</p><h3>@reduxjs/toolkit</h3><p>This package provides:</p><ul><li>configureStore()</li><li>createSlice()</li><li>createAsyncThunk()</li><li>RTK Query</li></ul><p>It is the core Redux Toolkit library.</p><h3>react-redux</h3><p>This package connects React with Redux.</p><p>It provides:</p><ul><li>Provider</li><li>useSelector()</li><li>useDispatch()</li></ul><p>RTK Query also relies on React Redux because its generated hooks access the Redux Store.</p><h3>Project Structure</h3><p>A clean project structure keeps API-related code organized.</p><pre>src<br>│<br>├── app<br>│   └── store.js<br>│<br>├── services<br>│   └── api.js<br>│<br>├── features<br>│<br>├── components<br>│<br>├── App.jsx<br>│<br>└── main.jsx</pre><h3>Understanding the Folder Structure</h3><p><strong>app</strong></p><p>Contains the Redux Store configuration.</p><p><strong>services</strong></p><p>Contains RTK Query API definitions.</p><p>Keeping APIs inside a dedicated folder makes them reusable throughout the application.</p><h3>Understanding the Setup Process</h3><p>Setting up RTK Query involves five major steps:</p><ol><li>Create an API Slice.</li><li>Register the API reducer.</li><li>Add RTK Query middleware.</li><li>Wrap React with the Provider.</li><li>Use generated Hooks inside components.</li></ol><p>We’ll explore each of these steps in detail in the upcoming articles.</p><h3>Why Do We Create an API Slice?</h3><p>Earlier, we learned about feature slices like:</p><ul><li>User Slice</li><li>Counter Slice</li><li>Todo Slice</li></ul><p>RTK Query introduces another type of slice called an <strong>API Slice</strong>.</p><p>Instead of managing local application state, an API Slice manages server data.</p><p>Its responsibilities include:</p><ul><li>Fetching data</li><li>Caching responses</li><li>Refetching when needed</li><li>Invalidating cache</li><li>Tracking loading state</li><li>Tracking errors</li></ul><p>Think of it as a dedicated manager for all API communication.</p><h3>Understanding the Overall Architecture</h3><p>Once RTK Query is configured, the architecture looks like this:</p><pre>React Component<br>        │<br>        ▼<br>Generated Hook<br>        │<br>        ▼<br>RTK Query API Slice<br>        │<br>        ▼<br>Redux Store<br>        │<br>        ▼<br>Middleware<br>        │<br>        ▼<br>Backend Server</pre><p>Every API request follows this predictable path.</p><p>Because RTK Query sits between React and your backend, it can automatically cache responses and optimize network requests.</p><h3>Common Beginner Questions</h3><h3>Is RTK Query a replacement for Axios?</h3><p>Not exactly.</p><p>RTK Query is a data fetching and caching solution.</p><p>It uses fetch() internally by default, but it can also work with custom base queries if needed.</p><p>Many developers stop using Axios after adopting RTK Query because RTK Query already handles most of the problems Axios users solve manually.</p><h3>Does RTK Query replace Redux?</h3><p>No.</p><p>RTK Query is part of Redux Toolkit.</p><p>Redux manages application state.</p><p>RTK Query manages <strong>server state</strong>.</p><p>They work together seamlessly.</p><h3>Can I use RTK Query without Redux Toolkit?</h3><p>No.</p><p>RTK Query is built specifically for Redux Toolkit.</p><p>It depends on the Redux Store to cache and manage server data.</p><h3>Should every API call use RTK Query?</h3><p>In most React applications, yes.</p><p>If your application communicates frequently with a backend, RTK Query is an excellent choice because it reduces boilerplate, improves performance, and provides consistent API management.</p><h3>Best Practices Before You Start</h3><p>Before writing your first RTK Query API, keep these recommendations in mind:</p><ul><li>Create one API Slice for related endpoints whenever possible.</li><li>Keep API definitions inside a dedicated services folder.</li><li>Let RTK Query manage server state instead of duplicating it in Redux slices.</li><li>Use feature slices for UI or client-side state, and use RTK Query for data that comes from the server.</li><li>Keep your API layer centralized to make maintenance easier as your project grows.</li></ul><h3>Key Takeaways</h3><p>Let’s summarize what you’ve learned in this introductory guide:</p><ul><li>RTK Query is a powerful API fetching and caching solution built into Redux Toolkit.</li><li>It dramatically reduces boilerplate by generating React Hooks automatically.</li><li>It handles caching, loading states, error handling, and refetching for you.</li><li>It integrates directly with the Redux Store and works alongside your existing slices.</li><li>A clean project structure makes your API layer easier to maintain and scale.</li><li>Setting up RTK Query involves creating an API Slice, registering its reducer and middleware, and then using the generated hooks inside React components.</li></ul><h3>What’s Next?</h3><p>Now that you understand <strong>what RTK Query is</strong> and <strong>why it exists</strong>, it’s time to configure it in a real React application.</p><p>In the next article, we’ll build the complete setup step by step and explain every line of code.</p><p>You’ll learn:</p><ul><li>Creating your first API Slice using createApi()</li><li>Understanding fetchBaseQuery()</li><li>Registering the API reducer inside the Redux Store</li><li>Adding RTK Query middleware</li><li>Connecting everything with React</li><li>Why every line of code is necessary</li><li>Common setup mistakes and how to avoid them</li></ul><p>By the end of the next article, your React project will be fully configured with RTK Query and ready to fetch data from real APIs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=281575953aa7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redux Toolkit Query (RTK Query) — Complete Setup Guide (Step-by-Step with Detailed Code…]]></title>
            <link>https://medium.com/@wm4012388/redux-toolkit-query-rtk-query-complete-setup-guide-step-by-step-with-detailed-code-c549647c1054?source=rss-111c7c60297c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c549647c1054</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux-toolkit]]></category>
            <dc:creator><![CDATA[Wali Muhammad]]></dc:creator>
            <pubDate>Mon, 20 Jul 2026 16:09:00 GMT</pubDate>
            <atom:updated>2026-07-20T16:09:00.526Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vlT4xivFstvcas-DnawrvQ.png" /></figure><h3>Redux Toolkit Query (RTK Query) — Complete Setup Guide (Step-by-Step with Detailed Code Explanation)</h3><h3>Introduction</h3><p>In the previous article, we learned what <strong>Redux Toolkit Query (RTK Query)</strong> is, why it was introduced, and how it simplifies API communication in React applications.</p><p>Now it’s time to implement it in a real project.</p><p>Many tutorials simply show a few code snippets and expect readers to understand everything automatically. However, beginners often struggle because they don’t know <strong>why each file is created, why each function is imported, or how all the files work together</strong>.</p><p>In this guide, we’ll build the complete RTK Query setup from scratch. Every file, every line of code, every import, and every configuration option will be explained in simple language.</p><p>By the end of this article, you’ll have a fully configured RTK Query project and a solid understanding of how everything works behind the scenes.</p><h3>What We Are Going to Build</h3><p>Our setup will communicate with the following API:</p><pre>https://jsonplaceholder.typicode.com/users</pre><p>This free API returns a list of users, making it perfect for learning RTK Query.</p><p>The setup process consists of six major steps:</p><ol><li>Install the required packages.</li><li>Create the API Slice.</li><li>Configure the Redux Store.</li><li>Register the RTK Query Middleware.</li><li>Connect Redux with React.</li><li>Fetch data using generated Hooks.</li></ol><p>Let’s begin.</p><h3>Final Project Structure</h3><p>Before writing any code, let’s organize our project.</p><pre>src<br>│<br>├── app<br>│   └── store.js<br>│<br>├── services<br>│   └── api.js<br>│<br>├── components<br>│   └── Users.jsx<br>│<br>├── App.jsx<br>│<br>└── main.jsx</pre><p>Each file has a specific responsibility.</p><ul><li><strong>api.js</strong> defines all API endpoints.</li><li><strong>store.js</strong> creates the Redux Store.</li><li><strong>main.jsx</strong> connects Redux with React.</li><li><strong>Users.jsx</strong> displays API data.</li><li><strong>App.jsx</strong> renders the component.</li></ul><p>Keeping API-related code inside a dedicated <strong>services</strong> folder makes projects easier to maintain as they grow.</p><h3>Step 1 — Install Required Packages</h3><p>If Redux Toolkit isn’t already installed, run:</p><pre>npm install @reduxjs/toolkit react-redux</pre><h3>Why do we need these packages?</h3><h3>@reduxjs/toolkit</h3><p>This package provides everything needed to build a Redux application, including:</p><ul><li>configureStore()</li><li>createSlice()</li><li>createAsyncThunk()</li><li>createApi() (RTK Query)</li></ul><p>Without this package, RTK Query cannot work.</p><h3>react-redux</h3><p>This package connects React with Redux.</p><p>It provides:</p><ul><li>Provider</li><li>useSelector</li><li>useDispatch</li></ul><p>RTK Query also relies on React Redux because the generated query hooks access the Redux Store.</p><h3>Step 2 — Create the API Slice</h3><p>Create the following file:</p><pre>src/services/api.js</pre><p>Now add the following code.</p><pre>import { createApi, fetchBaseQuery } from &quot;@reduxjs/toolkit/query/react&quot;;</pre><pre>export const api = createApi({<br>  reducerPath: &quot;api&quot;,</pre><pre>  baseQuery: fetchBaseQuery({<br>    baseUrl: &quot;https://jsonplaceholder.typicode.com/&quot;,<br>  }),</pre><pre>  endpoints: (builder) =&gt; ({<br>    getUsers: builder.query({<br>      query: () =&gt; &quot;users&quot;,<br>    }),<br>  }),<br>});</pre><pre>export const { useGetUsersQuery } = api;</pre><p>Let’s understand every line.</p><h3>Import createApi</h3><pre>import { createApi } from &quot;@reduxjs/toolkit/query/react&quot;;</pre><p>createApi() is the heart of RTK Query.</p><p>It creates an API Slice that manages:</p><ul><li>Fetching data</li><li>Caching responses</li><li>Loading states</li><li>Error states</li><li>Generated React Hooks</li></ul><p>Think of it as the central manager for all your backend communication.</p><h3>Import fetchBaseQuery</h3><pre>import { fetchBaseQuery } from &quot;@reduxjs/toolkit/query/react&quot;;</pre><p>fetchBaseQuery() is a lightweight wrapper around the browser&#39;s built-in fetch() function.</p><p>Instead of writing fetch() repeatedly for every request, you define a base URL once and reuse it for all endpoints.</p><h3>Create the API Slice</h3><pre>export const api = createApi({</pre><p>This creates an API Slice and exports it so the Redux Store can register it.</p><h3>reducerPath</h3><pre>reducerPath: &quot;api&quot;,</pre><p>Every Redux reducer needs a unique key inside the Store.</p><p>Here, RTK Query stores all API-related state under:</p><pre>state.api</pre><p>Inside this section, RTK Query keeps cached data, loading status, subscriptions, and metadata.</p><h3>baseQuery</h3><pre>baseQuery: fetchBaseQuery({<br>  baseUrl: &quot;https://jsonplaceholder.typicode.com/&quot;,<br>}),</pre><p>This defines the common base URL for every request.</p><p>Instead of writing:</p><pre>https://jsonplaceholder.typicode.com/users</pre><p>every time, we only specify:</p><pre>users</pre><p>inside our endpoints.</p><p>RTK Query automatically combines them.</p><h3>endpoints</h3><pre>endpoints: (builder) =&gt; ({</pre><p>This section contains every API endpoint your application will use.</p><p>Think of it as a collection of all backend operations.</p><h3>builder.query</h3><pre>getUsers: builder.query({</pre><p>builder.query() creates a <strong>GET request</strong>.</p><p>Queries are used whenever you want to retrieve data from a server.</p><h3>query()</h3><pre>query: () =&gt; &quot;users&quot;,</pre><p>This returns the endpoint path.</p><p>RTK Query combines it with the base URL.</p><p>Result:</p><pre>https://jsonplaceholder.typicode.com/users</pre><h3>Generated Hook</h3><pre>export const {<br>  useGetUsersQuery,<br>} = api;</pre><p>One of RTK Query’s best features is automatic Hook generation.</p><p>Instead of writing custom hooks manually, RTK Query creates them automatically.</p><p>We’ll use this Hook inside our React component.</p><h3>Step 3 — Configure the Redux Store</h3><p>Create:</p><pre>src/app/store.js</pre><p>Add the following code.</p><pre>import { configureStore } from &quot;@reduxjs/toolkit&quot;;</pre><pre>import { api } from &quot;../services/api&quot;;</pre><pre>export const store = configureStore({<br>  reducer: {<br>    [api.reducerPath]: api.reducer,<br>  },</pre><pre>  middleware: (getDefaultMiddleware) =&gt;<br>    getDefaultMiddleware().concat(api.middleware),<br>});</pre><p>Let’s understand every line.</p><h3>Import the API Slice</h3><pre>import { api } from &quot;../services/api&quot;;</pre><p>We import the API Slice so Redux knows about our endpoints.</p><h3>Register the Reducer</h3><pre>reducer: {<br>  [api.reducerPath]: api.reducer,<br>},</pre><p>This registers RTK Query inside the Redux Store.</p><p>Since:</p><pre>reducerPath: &quot;api&quot;</pre><p>the Redux Store now contains:</p><pre>state.api</pre><p>RTK Query stores cached API data here.</p><h3>Step 4 — Add RTK Query Middleware</h3><p>This line is extremely important.</p><pre>middleware: (getDefaultMiddleware) =&gt;<br>  getDefaultMiddleware().concat(api.middleware),</pre><p>Many beginners skip this line and wonder why RTK Query doesn’t work correctly.</p><p>The middleware is responsible for:</p><ul><li>Sending API requests</li><li>Caching responses</li><li>Automatic refetching</li><li>Cache invalidation</li><li>Polling</li><li>Request cancellation</li><li>Subscription management</li></ul><p>Without this middleware, RTK Query loses many of its most powerful features.</p><h3>Step 5 — Connect Redux with React</h3><p>Open:</p><pre>src/main.jsx</pre><p>Replace it with:</p><pre>import React from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom/client&quot;;</pre><pre>import { Provider } from &quot;react-redux&quot;;</pre><pre>import { store } from &quot;./app/store&quot;;</pre><pre>import App from &quot;./App&quot;;</pre><pre>ReactDOM.createRoot(document.getElementById(&quot;root&quot;)).render(<br>  &lt;Provider store={store}&gt;<br>    &lt;App /&gt;<br>  &lt;/Provider&gt;<br>);</pre><h3>Why Provider?</h3><p>Provider makes the Redux Store available to every React component.</p><p>Since RTK Query stores its data inside Redux, every generated Hook needs access to the Store.</p><p>Without the Provider, Hooks such as useGetUsersQuery() will throw an error because they cannot access the Redux context.</p><h3>Step 6 — Fetch Data Inside React</h3><p>Create:</p><pre>src/components/Users.jsx</pre><p>Add the following code.</p><pre>import { useGetUsersQuery } from &quot;../services/api&quot;;</pre><pre>const Users = () =&gt; {</pre><pre>  const {<br>    data,<br>    error,<br>    isLoading,<br>  } = useGetUsersQuery();</pre><pre>  if (isLoading) {<br>    return &lt;h2&gt;Loading...&lt;/h2&gt;;<br>  }</pre><pre>  if (error) {<br>    return &lt;h2&gt;Something went wrong.&lt;/h2&gt;;<br>  }</pre><pre>  return (<br>    &lt;div&gt;<br>      {data.map((user) =&gt; (<br>        &lt;p key={user.id}&gt;<br>          {user.name}<br>        &lt;/p&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>export default Users;</pre><p>Let’s understand everything.</p><h3>Import the Generated Hook</h3><pre>import { useGetUsersQuery } from &quot;../services/api&quot;;</pre><p>Remember, RTK Query created this Hook automatically when we defined the endpoint.</p><p>We didn’t write it ourselves.</p><h3>Call the Hook</h3><pre>const {<br>  data,<br>  error,<br>  isLoading,<br>} = useGetUsersQuery();</pre><p>The Hook automatically:</p><ul><li>Sends the API request</li><li>Stores the response</li><li>Tracks loading state</li><li>Tracks errors</li><li>Caches the result</li></ul><p>No useEffect() or useState() is required.</p><h3>Loading State</h3><pre>if (isLoading) {<br>  return &lt;h2&gt;Loading...&lt;/h2&gt;;<br>}</pre><p>While the request is in progress, RTK Query sets:</p><pre>isLoading = true</pre><p>Once the response arrives, it becomes:</p><pre>false</pre><h3>Error State</h3><pre>if (error) {<br>  return &lt;h2&gt;Something went wrong.&lt;/h2&gt;;<br>}</pre><p>If the server fails or the internet connection is unavailable, RTK Query automatically populates the error object.</p><h3>Display Data</h3><pre>data.map((user) =&gt; (<br>  &lt;p key={user.id}&gt;<br>    {user.name}<br>  &lt;/p&gt;<br>))</pre><p>Once the API request succeeds, data contains the array of users returned by the server.</p><p>We simply render each user’s name.</p><h3>Step 7 — Render the Component</h3><p>Open:</p><pre>src/App.jsx</pre><p>Replace everything with:</p><pre>import Users from &quot;./components/Users&quot;;</pre><pre>function App() {<br>  return &lt;Users /&gt;;<br>}</pre><pre>export default App;</pre><p>Now run the project.</p><pre>npm run dev</pre><p>You should see a list of users fetched directly from the API.</p><h3>Complete Flow of RTK Query</h3><p>When the component renders, this is what happens behind the scenes:</p><pre>Users Component<br>        │<br>        ▼<br>useGetUsersQuery()<br>        │<br>        ▼<br>RTK Query<br>        │<br>        ▼<br>fetchBaseQuery()<br>        │<br>        ▼<br>API Request<br>        │<br>        ▼<br>Server Response<br>        │<br>        ▼<br>Redux Store Cache<br>        │<br>        ▼<br>React Re-renders</pre><p>This entire flow happens automatically without writing manual fetch logic.</p><h3>Common Beginner Mistakes</h3><p>When setting up RTK Query for the first time, these are the most common mistakes:</p><ul><li>Forgetting to register api.reducer in the Redux Store.</li><li>Forgetting to add api.middleware.</li><li>Importing the Hook from the wrong file.</li><li>Forgetting to wrap the application with Provider.</li><li>Using builder.query() for operations that should modify data (those should use builder.mutation()).</li><li>Assuming data is immediately available without checking isLoading.</li></ul><p>Checking these areas first can save a lot of debugging time.</p><h3>Best Practices</h3><p>As your application grows, following these practices will keep your code clean and scalable:</p><ul><li>Create a single API Slice for related endpoints.</li><li>Organize all API logic inside a dedicated services folder.</li><li>Let RTK Query manage server state instead of duplicating it in Redux slices.</li><li>Use descriptive endpoint names such as getUsers, getPosts, and createUser.</li><li>Always handle loading and error states to provide a better user experience.</li></ul><h3>Key Takeaways</h3><p>By completing this setup, you’ve learned how to:</p><ul><li>Install the packages required for RTK Query.</li><li>Create an API Slice using createApi().</li><li>Configure a shared baseQuery with fetchBaseQuery().</li><li>Define API endpoints using builder.query().</li><li>Register the API reducer in the Redux Store.</li><li>Add RTK Query middleware for caching and request management.</li><li>Connect the Redux Store to React using Provider.</li><li>Fetch data with automatically generated Hooks.</li><li>Display loading, error, and success states with minimal code.</li></ul><p>This setup forms the foundation of every RTK Query application. Once you understand it, adding more endpoints becomes straightforward.</p><h3>What’s Next?</h3><p>Now that your RTK Query setup is complete, the next step is to explore <strong>Queries and Mutations</strong> in detail.</p><p>In the next article, you’ll learn:</p><ul><li>The difference between builder.query() and builder.mutation().</li><li>Performing <strong>GET</strong>, <strong>POST</strong>, <strong>PUT</strong>, <strong>PATCH</strong>, and <strong>DELETE</strong> requests.</li><li>Passing parameters to endpoints.</li><li>Working with request bodies.</li><li>Automatically updating cached data after mutations.</li><li>Building a complete CRUD application using RTK Query.</li></ul><p>By the end of the next guide, you’ll be able to build production-ready React applications that communicate efficiently with real-world REST APIs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c549647c1054" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redux Toolkit (Core) — Part 8: Advanced Core Concepts (Payload, Action Creators, Reducers…]]></title>
            <link>https://medium.com/@wm4012388/redux-toolkit-core-part-8-advanced-core-concepts-payload-action-creators-reducers-5298905b3436?source=rss-111c7c60297c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5298905b3436</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[redux-toolkit]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Wali Muhammad]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 05:12:50 GMT</pubDate>
            <atom:updated>2026-07-19T05:12:50.833Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bSdSb_XJ5H7VmHS5JZQTug.png" /></figure><h3>Redux Toolkit (Core) — Part 8: Advanced Core Concepts (Payload, Action Creators, Reducers, Selectors, State Tree, Dispatch Flow &amp; Pure Functions)</h3><p>In the previous articles, we explored the fundamentals of Redux Toolkit by building a Counter application and a complete Todo CRUD project. Along the way, we learned how to create a Store, define Slices, connect React with Redux, and manage application state.</p><p>At this point, you already know how to <strong>use</strong> Redux Toolkit.</p><p>However, to become a confident Redux developer, it’s equally important to understand <strong>what happens behind the scenes</strong>.</p><p>Many beginners can write Redux Toolkit code but struggle to explain questions like:</p><ul><li>What exactly is a payload?</li><li>What is an action creator?</li><li>Why are reducers called reducers?</li><li>What is a selector?</li><li>What does the Redux State Tree look like?</li><li>How does dispatch actually work?</li><li>Why must reducers always be pure functions?</li></ul><p>Understanding these concepts will help you write cleaner Redux code, debug applications more effectively, and prepare you for advanced topics such as asynchronous actions using createAsyncThunk.</p><p>In this article, we’ll explore each of these concepts one by one with simple explanations and practical examples.</p><h3>Understanding Payload</h3><h3>One of the first terms you’ll encounter in Redux is the <strong>Payload</strong>.</h3><p>A payload is simply the <strong>data that travels with an action</strong>.</p><p>Think of it like a courier package.</p><p>Imagine you order a new laptop online.</p><p>The courier delivers a package to your home.</p><p>The courier itself isn’t the important part — the valuable item is what’s inside the package.</p><p>Redux actions work in exactly the same way.</p><p>The action is the courier.</p><p>The payload is the data inside it.</p><p>For example:</p><pre>dispatch(addTodo({<br>  id: 1,<br>  title: &quot;Learn Redux Toolkit&quot;,<br>  completed: false,<br>}));</pre><p>Here, the dispatched action contains a payload.</p><p>Inside the reducer:</p><pre>action.payload</pre><p>contains:</p><pre>{<br>  id: 1,<br>  title: &quot;Learn Redux Toolkit&quot;,<br>  completed: false,<br>}</pre><p>The reducer doesn’t care who sent the action.</p><p>It only uses the data stored inside the payload.</p><p>Payloads can contain almost any serializable JavaScript value, including:</p><ul><li>Strings</li><li>Numbers</li><li>Booleans</li><li>Objects</li><li>Arrays</li></ul><p>For example:</p><pre>dispatch(changeTheme(&quot;dark&quot;));</pre><p>Payload:</p><pre>&quot;dark&quot;</pre><p>Or:</p><pre>dispatch(deleteTodo(5));</pre><p>Payload:</p><pre>5</pre><p>Every time you dispatch an action with data, that data is carried inside the payload.</p><h3>What is an Action Creator?</h3><p>Imagine writing this every time you wanted to increment a counter:</p><pre>dispatch({<br>  type: &quot;counter/increment&quot;,<br>});</pre><p>This works, but manually writing action objects throughout your application becomes repetitive and increases the chance of mistakes.</p><p>Redux Toolkit solves this by automatically creating <strong>Action Creators</strong>.</p><p>Suppose your slice contains:</p><pre>reducers: {<br>  increment(state) {<br>    state.value += 1;<br>  },<br>}</pre><p>Redux Toolkit automatically generates:</p><pre>increment()</pre><p>Now you simply write:</p><pre>dispatch(increment());</pre><p>Instead of manually creating an action object.</p><p>Behind the scenes, Redux Toolkit converts it into:</p><pre>{<br>  type: &quot;counter/increment&quot;,<br>}</pre><p>If your reducer expects a payload:</p><pre>addTodo(state, action) {<br>  state.todos.push(action.payload);<br>}</pre><p>You can dispatch:</p><pre>dispatch(addTodo({<br>  id: 1,<br>  title: &quot;Study Redux&quot;,<br>}));</pre><p>Redux Toolkit automatically creates:</p><pre>{<br>  type: &quot;todo/addTodo&quot;,<br>  payload: {<br>    id: 1,<br>    title: &quot;Study Redux&quot;,<br>  },<br>}</pre><p>This automatic generation makes Redux Toolkit far more concise than traditional Redux.</p><h3>Understanding Reducers</h3><p>Reducers are responsible for updating the application’s state.</p><p>Whenever Redux receives an action, it sends that action to the appropriate reducer.</p><p>The reducer examines the action and decides how the state should change.</p><p>Example:</p><pre>increment(state) {<br>  state.value += 1;<br>}</pre><p>When Redux receives:</p><pre>dispatch(increment());</pre><p>the reducer runs and updates the counter.</p><p>Reducers should only contain logic related to updating state.</p><p>They should not:</p><ul><li>Call APIs</li><li>Generate random values</li><li>Read from localStorage</li><li>Modify the DOM</li></ul><p>Their only responsibility is to calculate the next state based on the current state and the received action.</p><p>Keeping reducers focused makes applications easier to test and debug.</p><h3>What are Selectors?</h3><p>As applications grow, the Redux Store becomes larger.</p><p>Imagine a Store like this:</p><pre>{<br>  user: {...},</pre><pre>  cart: {...},</pre><pre>  products: {...},</pre><pre>  orders: {...},</pre><pre>  notifications: {...},<br>}</pre><p>A component usually doesn’t need the entire Store.</p><p>Instead, it needs only a specific part.</p><p>That’s exactly what a <strong>Selector</strong> does.</p><p>A selector extracts only the required data.</p><p>Example:</p><pre>const cartItems = useSelector(<br>  state =&gt; state.cart.items<br>);</pre><p>Here, the component selects only the cart items.</p><p>Similarly:</p><pre>const user = useSelector(<br>  state =&gt; state.user<br>);</pre><p>Or:</p><pre>const theme = useSelector(<br>  state =&gt; state.theme<br>);</pre><p>Selectors help improve readability because components request only the data they actually use.</p><p>They also improve performance because React re-renders only when the selected value changes.</p><p>For larger applications, it’s common to create reusable selector functions:</p><pre>export const selectTodos = (state) =&gt; state.todo.todos;</pre><p>Then use them like this:</p><pre>const todos = useSelector(selectTodos);</pre><p>This keeps selector logic in one place and makes it easier to update later if the state structure changes.</p><h3>Understanding the Redux State Tree</h3><p>Everything stored inside Redux forms a single JavaScript object called the <strong>State Tree</strong>.</p><p>Imagine a blogging application.</p><p>Its Store might look like this:</p><pre>{<br>  auth: {<br>    user: {<br>      id: 1,<br>      name: &quot;John&quot;,<br>    },<br>    isLoggedIn: true,<br>  },</pre><pre>  posts: {<br>    list: [],<br>  },</pre><pre>  comments: {<br>    list: [],<br>  },</pre><pre>  theme: {<br>    mode: &quot;dark&quot;,<br>  },<br>}</pre><p>Notice how each slice owns its own section of the state.</p><p>You can think of the State Tree as the blueprint of your application’s global data.</p><p>Every slice contributes one branch to that tree.</p><p>This organization keeps data predictable and easy to navigate.</p><h3>Understanding Dispatch Flow</h3><p>Redux follows a predictable one-way data flow.</p><p>Whenever something changes, it always follows the same sequence.</p><p>Imagine a user clicks an <strong>Add Todo</strong> button.</p><p>The complete flow looks like this:</p><pre>User Clicks Button<br>        │<br>        ▼<br>dispatch(addTodo())<br>        │<br>        ▼<br>Redux Receives Action<br>        │<br>        ▼<br>Reducer Executes<br>        │<br>        ▼<br>Store Updates<br>        │<br>        ▼<br>useSelector Detects Change<br>        │<br>        ▼<br>React Re-renders</pre><p>Let’s understand each step.</p><p>First, the user interacts with the interface.</p><p>The component dispatches an action.</p><p>Redux receives the action and forwards it to the correct reducer.</p><p>The reducer calculates the next state.</p><p>Redux updates the Store.</p><p>React components using useSelector() notice that the selected state has changed.</p><p>React automatically re-renders those components.</p><p>Because every update follows this same predictable path, Redux applications are easier to debug than applications where state changes unpredictably.</p><h3>What are Pure Functions?</h3><p>One of Redux’s most important rules is that reducers should always be <strong>Pure Functions</strong>.</p><p>A pure function is a function that always produces the same output for the same input and does not cause side effects.</p><p>For example:</p><pre>function add(a, b) {<br>  return a + b;<br>}</pre><p>If you call:</p><pre>add(2, 3)</pre><p>it will always return:</p><pre>5</pre><p>No matter how many times you execute it.</p><p>Now consider this function:</p><pre>function randomNumber() {<br>  return Math.random();<br>}</pre><p>Every time you call it, the result is different.</p><p>This is <strong>not</strong> a pure function.</p><p>Similarly:</p><pre>function currentTime() {<br>  return new Date();<br>}</pre><p>also returns a different value every time.</p><p>Reducers should avoid these kinds of operations.</p><p>A reducer should depend only on:</p><ul><li>Current State</li><li>Received Action</li></ul><p>and return the next state.</p><p>Nothing more.</p><p>This predictability allows Redux DevTools to record actions, replay them, and even perform time-travel debugging.</p><h3>Why Pure Functions Matter</h3><p>Imagine two developers are debugging the same application.</p><p>If reducers generate random values or call APIs, the state may change differently every time the application runs.</p><p>Finding bugs becomes extremely difficult.</p><p>Pure reducers guarantee that the same action and the same state will always produce the same result.</p><p>This makes Redux applications predictable, reliable, and much easier to maintain.</p><h3>Putting Everything Together</h3><p>Let’s connect all the concepts we’ve learned.</p><p>Suppose a user clicks an <strong>Add Todo</strong> button.</p><ol><li>The React component calls an action creator.</li><li>The action creator returns an action object.</li><li>The action contains a payload.</li><li>The action is dispatched.</li><li>Redux forwards the action to the reducer.</li><li>The reducer creates the next state.</li><li>The Store is updated.</li><li>useSelector() detects the updated state.</li><li>React automatically re-renders the affected components.</li></ol><p>This predictable cycle is the foundation of every Redux Toolkit application.</p><h3>Common Beginner Mistakes</h3><p>As you begin building larger applications, keep these points in mind:</p><ul><li>Don’t modify Redux state outside reducers.</li><li>Don’t call APIs directly inside reducers.</li><li>Don’t store unnecessary UI state in Redux if useState() is sufficient.</li><li>Don’t access the entire Store when you only need one small value.</li><li>Always use meaningful action names and keep reducers focused on a single responsibility.</li><li>Create reusable selectors for frequently accessed state to keep components clean.</li></ul><p>Following these practices will make your Redux applications easier to understand and scale.</p><h3>Key Takeaways</h3><p>Let’s summarize everything we’ve learned in this article:</p><ul><li>A <strong>Payload</strong> is the data carried inside an action.</li><li><strong>Action Creators</strong> generate action objects automatically, reducing boilerplate.</li><li><strong>Reducers</strong> receive actions and calculate the next application state.</li><li><strong>Selectors</strong> retrieve specific pieces of state from the Redux Store.</li><li>The <strong>State Tree</strong> is the complete object representing your application’s global state.</li><li>Every update follows the same <strong>Dispatch Flow</strong>, making Redux predictable and easier to debug.</li><li><strong>Pure Functions</strong> always produce the same output for the same input and avoid side effects, making reducers reliable and testable.</li></ul><p>Understanding these advanced core concepts will help you move beyond simply using Redux Toolkit and enable you to reason about how it works internally.</p><h3>What’s Next?</h3><p>Now that you have a strong understanding of Redux Toolkit’s core architecture, it’s time to learn how Redux handles <strong>asynchronous operations</strong>.</p><p>In the next article, we’ll explore one of Redux Toolkit’s most powerful features: <strong>createAsyncThunk()</strong>.</p><p>You’ll learn:</p><ul><li>Why asynchronous state management is different from synchronous updates.</li><li>How to fetch data from APIs.</li><li>Understanding pending, fulfilled, and rejected states.</li><li>Handling loading indicators and error messages.</li><li>Using extraReducers with asynchronous actions.</li><li>Building a complete API-driven project using Redux Toolkit.</li></ul><p>By the end of the next article, you’ll be able to integrate real backend APIs into your Redux applications confidently.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5298905b3436" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redux Toolkit (Core) — Part 7: Build a Complete Todo App with Redux Toolkit (CRUD, Multiple…]]></title>
            <link>https://medium.com/@wm4012388/redux-toolkit-core-part-7-build-a-complete-todo-app-with-redux-toolkit-crud-multiple-e297c01d6783?source=rss-111c7c60297c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e297c01d6783</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Wali Muhammad]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 05:12:04 GMT</pubDate>
            <atom:updated>2026-07-19T05:12:04.378Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yUYgMwZPMz-jnZdvnGsJ9g.png" /></figure><h3>Redux Toolkit (Core) — Part 7: Build a Complete Todo App with Redux Toolkit (CRUD, Multiple Reducers, IDs &amp; Best Practices)</h3><p>In the previous article, we built our first Redux Toolkit project — a simple Counter application. Although it helped us understand the Redux workflow, real-world applications are much more than incrementing and decrementing numbers.</p><p>Applications like Trello, Notion, Jira, Microsoft To Do, and Google Keep all revolve around managing collections of data. Users create items, update them, delete them, and mark them as completed. These are the operations you’ll perform in almost every application you build.</p><p>This is where a <strong>Todo Application</strong> becomes one of the best learning projects for Redux Toolkit.</p><p>Unlike the Counter App, this project introduces <strong>CRUD operations</strong>, <strong>arrays in Redux state</strong>, <strong>payloads</strong>, <strong>multiple reducers</strong>, <strong>unique IDs</strong>, and <strong>best practices</strong> used in production applications.</p><p>By the end of this article, you’ll understand how to manage real-world data using Redux Toolkit while keeping your code clean, organized, and scalable.</p><h3>What Does CRUD Mean?</h3><p>Before writing any code, let’s understand one of the most common terms in software development: <strong>CRUD</strong>.</p><p>CRUD stands for:</p><ul><li><strong>C</strong> — Create</li><li><strong>R</strong> — Read</li><li><strong>U</strong> — Update</li><li><strong>D</strong> — Delete</li></ul><p>Almost every modern application performs these four operations.</p><p>Imagine you’re using a task management app.</p><p>You create a new task.</p><p>You view all tasks.</p><p>You edit a task.</p><p>You delete a task.</p><p>That’s CRUD.</p><p>Our Todo application will implement all four operations using Redux Toolkit.</p><h3>Project Structure</h3><p>We’ll follow the same feature-based folder structure introduced earlier.</p><pre>src<br>│<br>├── app<br>│   └── store.js<br>│<br>├── features<br>│   └── todo<br>│       └── todoSlice.js<br>│<br>├── components<br>│   └── Todo.jsx<br>│<br>├── App.jsx<br>│<br>└── main.jsx</pre><p>As projects grow, keeping Redux code inside the <strong>features</strong> folder makes the application much easier to maintain.</p><h3>Step 1 — Designing the State</h3><p>Before writing reducers, we first need to decide what our state should look like.</p><p>Each todo should contain:</p><ul><li>A unique ID</li><li>Task title</li><li>Completion status</li></ul><p>Our initial state looks like this:</p><pre>const initialState = {<br>  todos: [],<br>};</pre><p>Initially, the array is empty because the user hasn’t added any tasks yet.</p><p>After adding tasks, the state may look like this:</p><pre>{<br>  todos: [<br>    {<br>      id: 1,<br>      title: &quot;Learn Redux Toolkit&quot;,<br>      completed: false,<br>    },<br>    {<br>      id: 2,<br>      title: &quot;Build Todo App&quot;,<br>      completed: true,<br>    },<br>  ],<br>}</pre><p>Notice that each todo is an object containing multiple properties instead of just a string. This gives us the flexibility to store additional information later, such as due dates or priorities.</p><h3>Step 2 — Creating the Todo Slice</h3><p>Now let’s create our slice.</p><pre>import { createSlice } from &quot;@reduxjs/toolkit&quot;;</pre><pre>const initialState = {<br>  todos: [],<br>};</pre><pre>const todoSlice = createSlice({<br>  name: &quot;todo&quot;,</pre><pre>  initialState,</pre><pre>  reducers: {</pre><pre>    addTodo(state, action) {<br>      state.todos.push(action.payload);<br>    },</pre><pre>    deleteTodo(state, action) {<br>      state.todos = state.todos.filter(<br>        todo =&gt; todo.id !== action.payload<br>      );<br>    },</pre><pre>    toggleTodo(state, action) {<br>      const todo = state.todos.find(<br>        todo =&gt; todo.id === action.payload<br>      );</pre><pre>      if (todo) {<br>        todo.completed = !todo.completed;<br>      }<br>    },</pre><pre>    updateTodo(state, action) {</pre><pre>      const todo = state.todos.find(<br>        todo =&gt; todo.id === action.payload.id<br>      );</pre><pre>      if (todo) {<br>        todo.title = action.payload.title;<br>      }</pre><pre>    },</pre><pre>  },</pre><pre>});</pre><pre>export const {<br>  addTodo,<br>  deleteTodo,<br>  toggleTodo,<br>  updateTodo,<br>} = todoSlice.actions;</pre><pre>export default todoSlice.reducer;</pre><p>Although this slice contains four reducers, Redux Toolkit automatically generates four action creators for us. We don’t need to write separate action files as we did in traditional Redux.</p><h3>Understanding Every Reducer</h3><p>Let’s examine each reducer individually.</p><h3>Add Todo</h3><pre>addTodo(state, action) {<br>    state.todos.push(action.payload);<br>}</pre><p>Whenever a user creates a new task, we dispatch the addTodo action.</p><p>The new todo object is available inside action.payload.</p><p>We simply push it into the todos array.</p><p>Redux Toolkit allows this because Immer safely creates a new immutable state behind the scenes.</p><h3>Delete Todo</h3><pre>deleteTodo(state, action) {<br>    state.todos = state.todos.filter(<br>        todo =&gt; todo.id !== action.payload<br>    );<br>}</pre><p>Instead of removing items manually, we use JavaScript’s filter() method.</p><p>The reducer keeps every todo whose ID does <strong>not</strong> match the ID we want to delete.</p><p>The result is a brand-new array without the selected task.</p><h3>Toggle Todo</h3><pre>toggleTodo(state, action) {</pre><pre>    const todo = state.todos.find(<br>        todo =&gt; todo.id === action.payload<br>    );</pre><pre>    if(todo){<br>        todo.completed = !todo.completed;<br>    }</pre><pre>}</pre><p>First, we search for the todo using its ID.</p><p>If we find it, we reverse the completed value.</p><pre>false</pre><p>becomes</p><pre>true</pre><p>and vice versa.</p><p>This is how applications allow users to mark tasks as completed.</p><h3>Update Todo</h3><pre>updateTodo(state, action) {</pre><pre>    const todo = state.todos.find(<br>        todo =&gt; todo.id === action.payload.id<br>    );</pre><pre>    if(todo){<br>        todo.title = action.payload.title;<br>    }</pre><pre>}</pre><p>This reducer changes the title of an existing todo.</p><p>The payload contains both:</p><ul><li>The ID</li><li>The updated title</li></ul><p>The reducer finds the matching todo and replaces its title.</p><h3>Understanding Payload</h3><p>You’ll notice every reducer receives:</p><pre>action</pre><p>The action contains something called the <strong>payload</strong>.</p><p>A payload is simply the data sent with an action.</p><p>For example:</p><pre>dispatch(addTodo({<br>    id: 1,<br>    title: &quot;Learn Redux&quot;,<br>    completed: false,<br>}));</pre><p>Inside the reducer:</p><pre>action.payload</pre><p>contains:</p><pre>{<br>   id: 1,<br>   title: &quot;Learn Redux&quot;,<br>   completed: false<br>}</pre><p>Think of the payload as the package that carries information from your React component to the Redux Store.</p><h3>Why Do We Need IDs?</h3><p>Many beginners wonder why every todo needs an ID.</p><p>Imagine two tasks:</p><pre>Read Book</pre><pre>Read Book</pre><p>Now suppose you want to delete one of them.</p><p>Which one should Redux remove?</p><p>There’s no way to know.</p><p>Unique IDs solve this problem.</p><p>Example:</p><pre>{<br>    id: 101,<br>    title: &quot;Read Book&quot;<br>}</pre><pre>{<br>    id: 205,<br>    title: &quot;Read Book&quot;<br>}</pre><p>Even though the titles are identical, their IDs are different.</p><p>Redux can now identify exactly which todo to update or delete.</p><p>In real applications, IDs often come from a backend API or a database. For local projects, you can use Date.now(), crypto.randomUUID(), or a library like nanoid.</p><h3>Working with Multiple Reducers</h3><p>Our slice currently contains four reducers:</p><ul><li>addTodo</li><li>deleteTodo</li><li>toggleTodo</li><li>updateTodo</li></ul><p>Each reducer has only one responsibility.</p><p>This follows the <strong>Single Responsibility Principle</strong>, making the code easier to read, debug, and test.</p><p>As your application grows, you might add additional reducers such as:</p><ul><li>clearCompleted</li><li>markAllCompleted</li><li>sortTodos</li><li>setFilter</li></ul><p>Each reducer should perform one specific task instead of trying to handle multiple responsibilities.</p><h3>Connecting the Slice to the Store</h3><p>Every slice must be registered inside the Redux Store.</p><pre>import { configureStore } from &quot;@reduxjs/toolkit&quot;;</pre><pre>import todoReducer from &quot;../features/todo/todoSlice&quot;;</pre><pre>export const store = configureStore({</pre><pre>  reducer: {</pre><pre>    todo: todoReducer,</pre><pre>  },</pre><pre>});</pre><p>Once registered, the Redux state becomes:</p><pre>{<br>   todo: {</pre><pre>      todos: []</pre><pre>   }<br>}</pre><p>Later, after adding tasks:</p><pre>{<br>   todo: {</pre><pre>      todos: [<br>        ...<br>      ]</pre><pre>   }<br>}</pre><p>This predictable structure makes it easy to retrieve data using useSelector().</p><h3>Reading Todos Inside React</h3><p>To display todos inside a component:</p><pre>const todos = useSelector(<br>    state =&gt; state.todo.todos<br>);</pre><p>Redux returns the array stored inside the Todo Slice.</p><p>Whenever a new todo is added or removed, React automatically re-renders the component with the latest data.</p><h3>Best Practices</h3><p>As your Redux applications grow, following best practices becomes increasingly important.</p><p>Here are some recommendations used in professional projects:</p><h3>Keep Reducers Small</h3><p>Each reducer should perform one specific task.</p><p>Avoid writing reducers that try to handle multiple responsibilities.</p><h3>Organize by Feature</h3><p>Instead of grouping files by type, group them by feature.</p><p>Good:</p><pre>features<br>│<br>├── auth<br>├── cart<br>├── products<br>└── todo</pre><p>This keeps related files together and improves scalability.</p><h3>Store Only Global State</h3><p>Redux is designed for application-wide data.</p><p>Avoid storing temporary UI state, such as whether a modal is open or whether a button is hovered.</p><p>Those values usually belong in local component state using useState().</p><h3>Keep State Serializable</h3><p>Redux state should contain plain JavaScript values like:</p><ul><li>Objects</li><li>Arrays</li><li>Strings</li><li>Numbers</li><li>Booleans</li></ul><p>Avoid storing DOM elements, functions, or class instances inside Redux.</p><h3>Use Meaningful Action Names</h3><p>Action names should clearly describe what they do.</p><p>Good examples:</p><ul><li>addTodo</li><li>deleteTodo</li><li>toggleTodo</li><li>updateTodo</li></ul><p>Avoid vague names such as change or modify.</p><p>Clear action names make debugging much easier, especially when using Redux DevTools.</p><h3>What You’ve Learned</h3><p>Congratulations! You have now built a realistic Redux Toolkit feature that goes beyond simple counters.</p><p>In this article, you learned:</p><ul><li>What CRUD operations are and why they’re fundamental to application development.</li><li>How to store arrays of objects inside Redux state.</li><li>How to create multiple reducers within a single slice.</li><li>How payloads carry data from React components to Redux reducers.</li><li>Why unique IDs are essential for updating and deleting items.</li><li>How to register a slice with the Redux Store.</li><li>How to read Redux state using useSelector().</li><li>Best practices that help keep Redux applications organized, scalable, and maintainable.</li></ul><p>This Todo project demonstrates patterns you’ll use in countless real-world applications, from e-commerce carts and inventory systems to project management tools and social media feeds.</p><h3>What’s Next?</h3><p>So far, you’ve learned how to manage synchronous state updates. The next step is to explore more advanced Redux Toolkit concepts.</p><p>In the next article, we’ll cover:</p><ul><li>Payloads in greater depth.</li><li>Action creators and how Redux Toolkit generates them.</li><li>Selectors and why they’re useful.</li><li>The complete Redux state tree.</li><li>Writing pure reducers.</li><li>How Redux processes actions internally.</li></ul><p>These concepts will deepen your understanding of Redux Toolkit and prepare you for asynchronous operations such as API calls using createAsyncThunk.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e297c01d6783" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redux Toolkit (Core) — Part 6: Build a Complete Counter App from Scratch (File by File Explanation)]]></title>
            <link>https://medium.com/@wm4012388/redux-toolkit-core-part-6-build-a-complete-counter-app-from-scratch-file-by-file-explanation-36d8af887e56?source=rss-111c7c60297c------2</link>
            <guid isPermaLink="false">https://medium.com/p/36d8af887e56</guid>
            <category><![CDATA[application]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[frontend-development]]></category>
            <dc:creator><![CDATA[Wali Muhammad]]></dc:creator>
            <pubDate>Sat, 18 Jul 2026 02:13:18 GMT</pubDate>
            <atom:updated>2026-07-18T02:13:18.935Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P-cRPlfUtapchNZIVC_hDw.png" /></figure><p>In the previous articles, we explored the core concepts of Redux Toolkit, including the Store, Slices, configureStore(), Provider, useSelector(), and useDispatch(). While understanding these concepts is important, the best way to truly learn Redux Toolkit is by building a real application.</p><p>In this article, we’ll create a <strong>Counter App</strong> from scratch. Although it’s a small project, it demonstrates the complete Redux Toolkit workflow that you’ll use in much larger applications.</p><p>By the end of this guide, you’ll understand how all the pieces fit together and how data flows through a Redux Toolkit application.</p><h3>Final Project Structure</h3><p>Before writing any code, let’s organize our project.</p><pre>src<br>│<br>├── app<br>│   └── store.js<br>│<br>├── features<br>│   └── counter<br>│       └── counterSlice.js<br>│<br>├── components<br>│   └── Counter.jsx<br>│<br>├── App.jsx<br>│<br>└── main.jsx</pre><p>Every file has a specific responsibility.</p><ul><li><strong>store.js</strong> creates the Redux Store.</li><li><strong>counterSlice.js</strong> contains the counter state and update logic.</li><li><strong>Counter.jsx</strong> displays and updates the counter.</li><li><strong>App.jsx</strong> renders the Counter component.</li><li><strong>main.jsx</strong> connects React to Redux using the Provider.</li></ul><p>Let’s build everything step by step.</p><h3>Step 1 — Create the Redux Store</h3><p>Create the following file:</p><pre>src/app/store.js</pre><p>Add the following code:</p><pre>import { configureStore } from &quot;@reduxjs/toolkit&quot;;<br>import counterReducer from &quot;../features/counter/counterSlice&quot;;</pre><pre>export const store = configureStore({<br>  reducer: {<br>    counter: counterReducer,<br>  },<br>});</pre><h3>Understanding Every Line</h3><h3>Import configureStore</h3><pre>import { configureStore } from &quot;@reduxjs/toolkit&quot;;</pre><p>This imports the function used to create the Redux Store.</p><p>Instead of manually configuring Redux, configureStore() automatically enables recommended defaults such as Redux DevTools and middleware.</p><h3>Import the Counter Reducer</h3><pre>import counterReducer from &quot;../features/counter/counterSlice&quot;;</pre><p>This imports the reducer created inside our Counter Slice.</p><p>Remember:</p><p>A reducer is responsible for updating a specific part of the state.</p><h3>Create the Store</h3><pre>export const store = configureStore({</pre><p>This creates the Redux Store and exports it so the rest of the application can use it.</p><h3>Register Reducers</h3><pre>reducer: {<br>  counter: counterReducer,<br>},</pre><p>The key counter becomes part of the Redux state.</p><p>Later, the Store will look like this:</p><pre>{<br>  counter: {<br>    value: 0<br>  }<br>}</pre><p>Whenever we write:</p><pre>state.counter.value</pre><p>Redux knows exactly where to find the counter value.</p><h3>Step 2 — Create the Counter Slice</h3><p>Create the file:</p><pre>src/features/counter/counterSlice.js</pre><p>Now add:</p><pre>import { createSlice } from &quot;@reduxjs/toolkit&quot;;</pre><pre>const initialState = {<br>  value: 0,<br>};</pre><pre>const counterSlice = createSlice({<br>  name: &quot;counter&quot;,<br>  initialState,<br>  reducers: {<br>    increment(state) {<br>      state.value += 1;<br>    },</pre><pre>    decrement(state) {<br>      state.value -= 1;<br>    },</pre><pre>    reset(state) {<br>      state.value = 0;<br>    },<br>  },<br>});</pre><pre>export const { increment, decrement, reset } = counterSlice.actions;</pre><pre>export default counterSlice.reducer;</pre><h3>Understanding Every Line</h3><h3>Import createSlice</h3><pre>import { createSlice } from &quot;@reduxjs/toolkit&quot;;</pre><p>This function creates:</p><ul><li>Reducer</li><li>Action Creators</li><li>Action Types</li></ul><p>Automatically.</p><h3>Create the Initial State</h3><pre>const initialState = {<br>  value: 0,<br>};</pre><p>This defines the default state when the application starts.</p><p>Initially:</p><pre>Counter = 0</pre><h3>Give the Slice a Name</h3><pre>name: &quot;counter&quot;,</pre><p>Redux uses this name when generating action types.</p><p>For example:</p><pre>counter/increment<br>counter/decrement<br>counter/reset</pre><h3>Create Reducers</h3><pre>increment(state) {<br>    state.value += 1;<br>}</pre><p>Whenever this reducer executes, the counter increases by one.</p><p>Similarly,</p><pre>decrement(state) {<br>    state.value -= 1;<br>}</pre><p>decreases the value.</p><p>Finally,</p><pre>reset(state) {<br>    state.value = 0;<br>}</pre><p>returns the counter to its initial value.</p><p>Although this appears to mutate the state directly, Redux Toolkit uses <strong>Immer</strong> internally to create immutable updates safely.</p><h3>Export Actions</h3><pre>export const { increment, decrement, reset } = counterSlice.actions;</pre><p>Redux Toolkit automatically creates action creators for every reducer.</p><p>These actions will later be dispatched from our React component.</p><h3>Export the Reducer</h3><pre>export default counterSlice.reducer;</pre><p>The Store needs this reducer to know how the counter state should change.</p><h3>Step 3 — Connect Redux to React</h3><p>Open:</p><pre>src/main.jsx</pre><p>Replace it with:</p><pre>import React from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom/client&quot;;</pre><pre>import { Provider } from &quot;react-redux&quot;;</pre><pre>import { store } from &quot;./app/store&quot;;</pre><pre>import App from &quot;./App&quot;;</pre><pre>ReactDOM.createRoot(document.getElementById(&quot;root&quot;)).render(<br>  &lt;Provider store={store}&gt;<br>    &lt;App /&gt;<br>  &lt;/Provider&gt;<br>);</pre><h3>Understanding Every Line</h3><h3>Import Provider</h3><pre>import { Provider } from &quot;react-redux&quot;;</pre><p>The Provider shares the Redux Store with every component inside the application.</p><h3>Import Store</h3><pre>import { store } from &quot;./app/store&quot;;</pre><p>This imports the Store we created earlier.</p><h3>Wrap App</h3><pre>&lt;Provider store={store}&gt;<br>    &lt;App /&gt;<br>&lt;/Provider&gt;</pre><p>Without the Provider, useSelector() and useDispatch() would not work because React components would have no access to the Store.</p><h3>Step 4 — Create the Counter Component</h3><p>Create:</p><pre>src/components/Counter.jsx</pre><p>Add the following code:</p><pre>import { useDispatch, useSelector } from &quot;react-redux&quot;;</pre><pre>import {<br>  increment,<br>  decrement,<br>  reset,<br>} from &quot;../features/counter/counterSlice&quot;;</pre><pre>const Counter = () =&gt; {</pre><pre>  const count = useSelector((state) =&gt; state.counter.value);</pre><pre>  const dispatch = useDispatch();</pre><pre>  return (<br>    &lt;div&gt;</pre><pre>      &lt;h1&gt;Counter : {count}&lt;/h1&gt;</pre><pre>      &lt;button onClick={() =&gt; dispatch(increment())}&gt;<br>        Increment<br>      &lt;/button&gt;</pre><pre>      &lt;button onClick={() =&gt; dispatch(decrement())}&gt;<br>        Decrement<br>      &lt;/button&gt;</pre><pre>      &lt;button onClick={() =&gt; dispatch(reset())}&gt;<br>        Reset<br>      &lt;/button&gt;</pre><pre>    &lt;/div&gt;<br>  );</pre><pre>};</pre><pre>export default Counter;</pre><h3>Understanding Every Line</h3><h3>Import Hooks</h3><pre>import { useDispatch, useSelector } from &quot;react-redux&quot;;</pre><ul><li>useSelector() reads data from the Store.</li><li>useDispatch() sends actions to Redux.</li></ul><h3>Import Actions</h3><pre>import {<br>  increment,<br>  decrement,<br>  reset,<br>} from &quot;../features/counter/counterSlice&quot;;</pre><p>These are the action creators automatically generated by Redux Toolkit.</p><h3>Read State</h3><pre>const count = useSelector(<br>  (state) =&gt; state.counter.value<br>);</pre><p>state represents the entire Redux Store.</p><p>Redux returns:</p><pre>state.counter.value</pre><p>which is currently:</p><pre>0</pre><h3>Get Dispatch Function</h3><pre>const dispatch = useDispatch();</pre><p>This function sends actions to Redux.</p><h3>Display Counter</h3><pre>&lt;h1&gt;Counter : {count}&lt;/h1&gt;</pre><p>Whenever the Store updates, React automatically re-renders this value.</p><h3>Increment Button</h3><pre>&lt;button<br>onClick={() =&gt; dispatch(increment())}<br>&gt;<br>Increment<br>&lt;/button&gt;</pre><p>Clicking the button dispatches the increment action.</p><p>Redux executes the reducer.</p><p>The Store updates.</p><p>React re-renders.</p><h3>Decrement Button</h3><pre>dispatch(decrement())</pre><p>This decreases the counter value by one.</p><h3>Reset Button</h3><pre>dispatch(reset())</pre><p>This returns the counter value to zero.</p><h3>Step 5 — Render the Component</h3><p>Open:</p><pre>src/App.jsx</pre><p>Replace everything with:</p><pre>import Counter from &quot;./components/Counter&quot;;</pre><pre>function App() {</pre><pre>  return (<br>    &lt;Counter /&gt;<br>  );</pre><pre>}</pre><pre>export default App;</pre><p>This simply renders our Counter component.</p><h3>Understanding the Complete Flow</h3><p>Let’s see what happens when the user clicks <strong>Increment</strong>.</p><pre>User Clicks Button<br>        │<br>        ▼<br>dispatch(increment())<br>        │<br>        ▼<br>Redux Receives Action<br>        │<br>        ▼<br>Counter Reducer Executes<br>        │<br>        ▼<br>Store Updates<br>        │<br>        ▼<br>useSelector Detects Change<br>        │<br>        ▼<br>React Re-renders Counter<br>        │<br>        ▼<br>Updated Value Appears</pre><p>Every Redux Toolkit application follows this same predictable flow.</p><h3>Expected Output</h3><p>When the application starts, you’ll see:</p><pre>Counter : 0</pre><pre>[ Increment ]</pre><pre>[ Decrement ]</pre><pre>[ Reset ]</pre><p>Click <strong>Increment</strong>:</p><pre>Counter : 1</pre><p>Click again:</p><pre>Counter : 2</pre><p>Click <strong>Decrement</strong>:</p><pre>Counter : 1</pre><p>Click <strong>Reset</strong>:</p><pre>Counter : 0</pre><p>Everything updates instantly because React automatically re-renders whenever the selected Redux state changes.</p><h3>Common Beginner Mistakes</h3><p>While building this project, beginners often run into a few common problems:</p><ul><li>Forgetting to wrap the app with Provider.</li><li>Registering the reducer with the wrong key in store.js.</li><li>Using the wrong selector path, such as state.value instead of state.counter.value.</li><li>Forgetting to export actions from the Slice.</li><li>Dispatching an action without calling useDispatch().</li></ul><p>If you encounter an error, check these areas first.</p><h3>What You’ve Learned</h3><p>Congratulations! You’ve built your first complete Redux Toolkit application.</p><p>More importantly, you now understand how each file contributes to the overall architecture:</p><ul><li>store.js creates the centralized Store.</li><li>counterSlice.js defines the counter state and update logic.</li><li>Provider makes the Store available to React.</li><li>useSelector() reads state from the Store.</li><li>useDispatch() sends actions to Redux.</li><li>Reducers update the state.</li><li>React automatically re-renders whenever the selected state changes.</li></ul><p>Although this project is simple, the same architecture is used in real-world applications such as dashboards, e-commerce platforms, banking systems, and enterprise software.</p><h3>What’s Next?</h3><p>The Counter App helped us understand the core Redux Toolkit workflow. In the next article, we’ll build a more realistic <strong>Todo Application</strong>.</p><p>You’ll learn how to:</p><ul><li>Add new todos.</li><li>Delete existing todos.</li><li>Mark todos as completed.</li><li>Update todo text.</li><li>Store arrays in Redux state.</li><li>Work with payloads.</li><li>Generate unique IDs.</li><li>Organize feature-based Redux code for real-world projects.</li></ul><p>By the end of the next project, you’ll move beyond simple numbers and start managing real application data with Redux Toolkit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36d8af887e56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redux Toolkit (Core) — Part 5: Connecting React with Redux Toolkit (Provider, useSelector &…]]></title>
            <link>https://medium.com/@wm4012388/redux-toolkit-core-part-5-connecting-react-with-redux-toolkit-provider-useselector-1ea255841b5c?source=rss-111c7c60297c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ea255841b5c</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Wali Muhammad]]></dc:creator>
            <pubDate>Sat, 18 Jul 2026 02:12:38 GMT</pubDate>
            <atom:updated>2026-07-18T02:12:38.404Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QMXiypSfClzxanu7cluDig.png" /></figure><h3>Redux Toolkit (Core) — Part 5: Connecting React with Redux Toolkit (Provider, useSelector &amp; useDispatch)</h3><p>In the previous articles, we learned how to install Redux Toolkit, create a Redux Store using configureStore(), and build our first Slice using createSlice().</p><p>At this stage, we have a Store that can hold data and a Slice that knows how to update it.</p><p>But there’s one important question left.</p><p><strong>How does React know that a Redux Store even exists?</strong></p><p>And once React knows about it, <strong>how do components read data from the Store or update it?</strong></p><p>This is exactly what we’ll learn in this article.</p><p>By the end of this guide, you’ll understand:</p><ul><li>Why the Provider component is required.</li><li>How useSelector() reads data from the Redux Store.</li><li>How useDispatch() updates the Store.</li><li>The complete Redux dispatch flow.</li><li>How React automatically re-renders when the Redux state changes.</li></ul><p>Let’s begin.</p><h3>Before Connecting React</h3><p>Currently, our application looks something like this:</p><pre>Redux Store<br>│<br>├── Counter State<br>├── User State<br>└── Theme State</pre><p>The Store exists.</p><p>But React components know nothing about it.</p><p>For example:</p><pre>App<br>│<br>├── Navbar<br>├── Home<br>├── Counter<br>└── Profile</pre><p>These components cannot access the Store because there is no connection between React and Redux.</p><p>We need a bridge.</p><p>That bridge is called the <strong>Provider</strong>.</p><h3>What is Provider?</h3><p>Provider is a React component provided by the <strong>react-redux</strong> package.</p><p>Its responsibility is simple.</p><p>It makes the Redux Store available to every React component inside your application.</p><p>Think of it like a Wi-Fi router.</p><p>Imagine an office.</p><p>The internet connection enters through one router.</p><p>Every employee connected to that router can access the internet.</p><p>Without the router:</p><p>No internet.</p><p>Similarly:</p><p>Without the Provider:</p><p>No component can access the Redux Store.</p><p>The Provider shares the Store with the entire React component tree.</p><h3>Where Do We Use Provider?</h3><p>The Provider is usually placed at the root of the application.</p><p>In a Vite React project, this is typically inside main.jsx.</p><pre>import React from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom/client&quot;;</pre><pre>import { Provider } from &quot;react-redux&quot;;</pre><pre>import { store } from &quot;./app/store&quot;;</pre><pre>import App from &quot;./App&quot;;</pre><pre>ReactDOM.createRoot(document.getElementById(&quot;root&quot;)).render(<br>  &lt;Provider store={store}&gt;<br>    &lt;App /&gt;<br>  &lt;/Provider&gt;<br>);</pre><p>Let’s understand this step by step.</p><p>First, we import the Provider.</p><pre>import { Provider } from &quot;react-redux&quot;;</pre><p>Next, we import the Redux Store we created earlier.</p><pre>import { store } from &quot;./app/store&quot;;</pre><p>Finally, we wrap our entire application inside the Provider.</p><pre>&lt;Provider store={store}&gt;<br>  &lt;App /&gt;<br>&lt;/Provider&gt;</pre><p>Notice the store prop.</p><pre>store={store}</pre><p>Here we’re telling the Provider:</p><blockquote><em>“This is the Redux Store. Share it with every component inside </em><em>&lt;App /&gt;.&quot;</em></blockquote><p>Now every component inside the application can access Redux.</p><h3>Why Wrap the Entire App?</h3><p>Imagine wrapping only one component.</p><pre>&lt;Provider store={store}&gt;<br>   &lt;Navbar /&gt;<br>&lt;/Provider&gt;</pre><pre>&lt;Home /&gt;</pre><p>Now:</p><ul><li>Navbar can use Redux.</li><li>Home cannot.</li></ul><p>That’s why we wrap the highest component possible.</p><p>Usually:</p><pre>&lt;App /&gt;</pre><p>Everything inside App automatically gets access to the Store.</p><h3>What is useSelector?</h3><p>Now that every component can access the Store, the next question is:</p><p>How do we <strong>read data</strong>?</p><p>Redux Toolkit provides a Hook called:</p><pre>useSelector()</pre><p>Its job is to read data from the Redux Store.</p><p>Think of it as a search function.</p><p>Whenever a component needs some information, it asks the Store using useSelector().</p><p>Example:</p><pre>import { useSelector } from &quot;react-redux&quot;;</pre><pre>const Counter = () =&gt; {</pre><pre>  const count = useSelector((state) =&gt; state.counter.value);</pre><pre>  return &lt;h1&gt;{count}&lt;/h1&gt;;</pre><pre>};</pre><p>Let’s understand this line.</p><pre>const count = useSelector((state) =&gt; state.counter.value);</pre><p>state represents the entire Redux Store.</p><p>Imagine your Store looks like this:</p><pre>{<br>   counter: {<br>      value: 10<br>   },</pre><pre>   user: {<br>      name: &quot;John&quot;<br>   }<br>}</pre><p>When you write:</p><pre>state.counter.value</pre><p>Redux returns:</p><pre>10</pre><p>If the value later becomes:</p><pre>25</pre><p>The component automatically displays:</p><pre>25</pre><p>No manual refresh.</p><p>No extra code.</p><p>React updates itself.</p><h3>Why is it Called useSelector?</h3><p>The word <strong>Selector</strong> means:</p><blockquote><em>Select only the data you need.</em></blockquote><p>Instead of reading the entire Store, components should read only the required data.</p><p>For example:</p><pre>const user = useSelector((state) =&gt; state.user);</pre><p>or</p><pre>const theme = useSelector((state) =&gt; state.theme);</pre><p>or</p><pre>const cartItems = useSelector((state) =&gt; state.cart.items);</pre><p>Each component selects only its own data.</p><p>This improves performance because React re-renders only when the selected data changes.</p><h3>What is useDispatch?</h3><p>Reading data is only half of Redux.</p><p>Applications also need to update data.</p><p>Suppose a user clicks:</p><pre>Increment</pre><p>How does Redux know the button was clicked?</p><p>The answer is:</p><p><strong>Dispatch</strong></p><p>Redux provides another Hook:</p><pre>useDispatch()</pre><p>Its responsibility is to send actions to Redux.</p><p>Example:</p><pre>import { useDispatch } from &quot;react-redux&quot;;</pre><pre>import { increment } from &quot;./counterSlice&quot;;</pre><pre>const Counter = () =&gt; {</pre><pre>  const dispatch = useDispatch();</pre><pre>  return (</pre><pre>    &lt;button onClick={() =&gt; dispatch(increment())}&gt;<br>      Increment<br>    &lt;/button&gt;</pre><pre>  );</pre><pre>};</pre><p>Let’s understand it.</p><p>First:</p><pre>const dispatch = useDispatch();</pre><p>This gives us access to Redux’s dispatch function.</p><p>Then:</p><pre>dispatch(increment());</pre><p>This sends the increment action to Redux.</p><p>Redux receives the action.</p><p>The reducer runs.</p><p>The Store updates.</p><p>React automatically re-renders.</p><h3>What Happens When We Dispatch?</h3><p>Let’s imagine the counter value is:</p><pre>0</pre><p>The user clicks:</p><pre>Increment</pre><p>React dispatches:</p><pre>dispatch(increment());</pre><p>Redux receives:</p><pre>counter/increment</pre><p>The reducer executes:</p><pre>state.value += 1;</pre><p>Now the Store becomes:</p><pre>1</pre><p>The UI automatically updates.</p><p>The user sees:</p><pre>1</pre><p>Everything happens within milliseconds.</p><h3>Understanding the Dispatch Flow</h3><p>One of Redux’s greatest strengths is its predictable data flow.</p><p>Every update follows the exact same path.</p><pre>User Clicks Button<br>        │<br>        ▼<br>dispatch(action)<br>        │<br>        ▼<br>Redux Receives Action<br>        │<br>        ▼<br>Reducer Executes<br>        │<br>        ▼<br>Store Updates<br>        │<br>        ▼<br>React Components Re-render</pre><p>Notice something important.</p><p>Data never jumps directly from a button to the UI.</p><p>Every update goes through the Store.</p><p>This makes debugging much easier because the flow is always predictable.</p><h3>The React Rendering Cycle</h3><p>Now let’s understand what happens after the Store changes.</p><p>Imagine your counter value is:</p><pre>0</pre><p>The component renders:</p><pre>Counter: 0</pre><p>The user clicks:</p><pre>Increment</pre><p>Redux updates the Store:</p><pre>Counter: 1</pre><p>React notices that the selected state has changed.</p><p>The component automatically renders again.</p><p>Now the screen shows:</p><pre>Counter: 1</pre><p>This process is called <strong>Re-rendering</strong>.</p><p>React doesn’t refresh the entire page.</p><p>It updates only the components whose selected Redux state changed.</p><p>This is one of the reasons React applications feel fast and responsive.</p><h3>Complete Flow in One Example</h3><p>Let’s combine everything we’ve learned.</p><p>Imagine the following component:</p><pre>import { useDispatch, useSelector } from &quot;react-redux&quot;;</pre><pre>import { increment } from &quot;./counterSlice&quot;;</pre><pre>function Counter() {</pre><pre>  const count = useSelector((state) =&gt; state.counter.value);</pre><pre>  const dispatch = useDispatch();</pre><pre>  return (</pre><pre>    &lt;&gt;<br>      &lt;h2&gt;{count}&lt;/h2&gt;</pre><pre>      &lt;button onClick={() =&gt; dispatch(increment())}&gt;<br>        Increment<br>      &lt;/button&gt;<br>    &lt;/&gt;</pre><pre>  );</pre><pre>}</pre><p>Here’s what happens step by step:</p><ol><li>The component reads the current counter value using useSelector().</li><li>React displays that value on the screen.</li><li>The user clicks the <strong>Increment</strong> button.</li><li>dispatch(increment()) sends an action to Redux.</li><li>Redux executes the increment reducer.</li><li>The Store updates the counter value.</li><li>useSelector() detects that the selected value has changed.</li><li>React re-renders only the Counter component.</li><li>The updated value appears immediately.</li></ol><p>This entire cycle is the foundation of how React and Redux work together.</p><h3>Common Beginner Mistakes</h3><p>When learning Redux Toolkit, beginners often encounter a few common issues:</p><ul><li>Forgetting to wrap the application with Provider.</li><li>Importing the wrong Store.</li><li>Using useSelector() outside the Provider.</li><li>Calling dispatch() without first using useDispatch().</li><li>Selecting the wrong state path, such as state.value instead of state.counter.value.</li></ul><p>Whenever you see errors like <strong>“could not find react-redux context value”</strong>, the first thing to check is whether your application is wrapped inside the Provider.</p><h3>Key Takeaways</h3><p>Let’s quickly review everything we’ve learned.</p><ul><li><strong>Provider</strong> connects React with the Redux Store and makes the Store available to every component.</li><li><strong>useSelector()</strong> reads data from the Redux Store.</li><li><strong>useDispatch()</strong> sends actions to Redux to update the state.</li><li>Every state update follows a predictable dispatch flow:<br><strong>Dispatch → Reducer → Store → React Re-render</strong>.</li><li>React automatically re-renders only the components whose selected Redux state changes.</li><li>This predictable architecture makes Redux applications easier to understand, debug, and scale.</li></ul><h3>What’s Next?</h3><p>Now that React is fully connected to Redux Toolkit, it’s time to build a complete application from scratch.</p><p>In the next article, we’ll create a <strong>Counter App</strong> using everything we’ve learned so far.</p><p>You’ll build it step by step while understanding:</p><ul><li>Project structure</li><li>Store configuration</li><li>Creating a Slice</li><li>Registering reducers</li><li>Using Provider</li><li>Reading state with useSelector()</li><li>Updating state with useDispatch()</li><li>How every file works together</li></ul><p>By the end of the next article, you’ll have your first fully functional Redux Toolkit application and a complete understanding of how all the core concepts fit together.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ea255841b5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redux Toolkit (Core) — Part 4: Understanding Slices in Redux Toolkit (Complete Beginner’s Guide)]]></title>
            <link>https://medium.com/@wm4012388/redux-toolkit-core-part-4-understanding-slices-in-redux-toolkit-complete-beginners-guide-f2e5627a7ebe?source=rss-111c7c60297c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2e5627a7ebe</guid>
            <category><![CDATA[redux-toolkit]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Wali Muhammad]]></dc:creator>
            <pubDate>Thu, 16 Jul 2026 16:40:44 GMT</pubDate>
            <atom:updated>2026-07-16T16:40:44.719Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*orp4bQv21Rbl6QY0EMdxLw.png" /></figure><p>In the previous article, we learned about the <strong>Redux Store</strong>, how configureStore() creates it, why it replaced the older createStore() API, and how middleware and Redux DevTools work behind the scenes.</p><p>At this point, our application has a Store, but it’s still empty. It doesn’t know how to store or update any data.</p><p>This is where <strong>Slices</strong> come in.</p><p>A Slice is one of the most important concepts in Redux Toolkit. In fact, you’ll spend most of your time creating and working with slices because they define <strong>what data your application stores and how that data can change</strong>.</p><p>In this article, we’ll understand what a Slice is, how createSlice() works, what initialState represents, how reducers update state, how actions are automatically generated, and why Redux Toolkit allows what appears to be direct state mutation.</p><h3>What is a Slice?</h3><p>A <strong>Slice</strong> is a portion of your application’s global state along with the logic that manages it.</p><p>Instead of putting all application data into one massive file, Redux Toolkit encourages splitting your state into smaller, manageable pieces.</p><p>Each piece is called a <strong>Slice</strong>.</p><p>Think of a pizza.</p><p>A whole pizza represents your entire Redux Store.</p><p>Each pizza slice represents one feature of your application.</p><pre>Redux Store<br>│<br>├── User Slice<br>├── Cart Slice<br>├── Product Slice<br>├── Theme Slice<br>└── Notification Slice</pre><p>Each slice is responsible for managing only its own data.</p><p>For example:</p><ul><li>The <strong>User Slice</strong> manages authentication and profile information.</li><li>The <strong>Cart Slice</strong> manages shopping cart items.</li><li>The <strong>Theme Slice</strong> manages light and dark mode.</li><li>The <strong>Notification Slice</strong> manages alerts and messages.</li></ul><p>This separation keeps your application clean, organized, and easier to maintain.</p><h3>Why Do We Need Slices?</h3><p>Imagine building an e-commerce application without slices.</p><p>You would have one giant reducer responsible for:</p><ul><li>User Login</li><li>Cart</li><li>Products</li><li>Orders</li><li>Wishlist</li><li>Theme</li><li>Notifications</li></ul><p>That file would quickly become hundreds or even thousands of lines long.</p><p>Finding bugs or adding new features would become difficult.</p><p>Slices solve this problem by organizing your application feature by feature.</p><p>Each feature gets its own file.</p><p>This makes the code easier to understand, easier to test, and easier to scale.</p><h3>What is createSlice()?</h3><p>Redux Toolkit provides a helper function called createSlice().</p><p>Its job is to create everything a feature needs in one place.</p><p>When you call createSlice(), Redux Toolkit automatically creates:</p><ul><li>The reducer</li><li>Action creators</li><li>Action types</li></ul><p>In traditional Redux, developers had to write all of these manually.</p><p>Redux Toolkit removes that repetitive work.</p><p>The basic structure looks like this:</p><pre>import { createSlice } from &quot;@reduxjs/toolkit&quot;;</pre><pre>const counterSlice = createSlice({<br>  name: &quot;counter&quot;,<br>  initialState: {<br>    value: 0,<br>  },<br>  reducers: {},<br>});</pre><p>Even though this is only a few lines of code, Redux Toolkit creates a lot behind the scenes.</p><p>Let’s understand each property one by one.</p><h3>Understanding the name Property</h3><p>Every slice needs a unique name.</p><pre>name: &quot;counter&quot;</pre><p>This name identifies the slice inside Redux.</p><p>It is also used when Redux generates action types.</p><p>For example, if you later create a reducer called increment, Redux Toolkit automatically creates an action type like this:</p><pre>counter/increment</pre><p>The first part comes from the slice name.</p><p>The second part comes from the reducer name.</p><p>This automatic naming helps avoid action type conflicts in large applications.</p><h3>What is initialState?</h3><p>Every slice needs some starting data.</p><p>That starting data is called the <strong>Initial State</strong>.</p><p>Think about a counter application.</p><p>Before the user clicks any button, the counter already has a value.</p><p>Usually:</p><pre>0</pre><p>That value becomes the initial state.</p><p>Example:</p><pre>initialState: {<br>  value: 0,<br>}</pre><p>Here, value starts at 0.</p><p>Similarly, a user slice might begin like this:</p><pre>initialState: {<br>  name: &quot;&quot;,<br>  email: &quot;&quot;,<br>  isLoggedIn: false,<br>}</pre><p>A shopping cart might begin like this:</p><pre>initialState: {<br>  items: [],<br>}</pre><p>The initial state defines what your application’s data looks like before any actions occur.</p><h3>Why is initialState Important?</h3><p>Imagine opening an online shopping website for the first time.</p><p>Your cart isn’t full.</p><p>It’s empty.</p><p>The cart doesn’t suddenly appear out of nowhere.</p><p>It starts with:</p><pre>items: []</pre><p>Likewise, before a user logs in:</p><pre>isLoggedIn: false</pre><p>Without an initial state, Redux wouldn’t know what values to use when the application starts.</p><h3>What are Reducers?</h3><p>Reducers define <strong>how the state changes</strong>.</p><p>They are functions that receive the current state and update it based on an action.</p><p>Example:</p><pre>reducers: {<br>  increment(state) {<br>    state.value += 1;<br>  },<br>}</pre><p>Here, the reducer is called increment.</p><p>Whenever it runs, it increases the counter value by one.</p><p>If the current value is:</p><pre>0</pre><p>After calling the reducer:</p><pre>1</pre><p>Call it again:</p><pre>2</pre><p>Reducers contain the business logic that describes how your application’s state should change.</p><h3>What are Actions?</h3><p>Reducers don’t run by themselves.</p><p>Something has to tell them <strong>when</strong> to update the state.</p><p>That “something” is called an <strong>Action</strong>.</p><p>An action simply describes <strong>what happened</strong>.</p><p>Examples include:</p><ul><li>User Logged In</li><li>Product Added</li><li>Item Removed</li><li>Theme Changed</li><li>Counter Incremented</li></ul><p>One of the best features of Redux Toolkit is that you don’t need to create action creators manually.</p><p>Suppose you define this reducer:</p><pre>reducers: {<br>  increment(state) {<br>    state.value += 1;<br>  },<br>}</pre><p>Redux Toolkit automatically generates an action creator for you.</p><pre>counterSlice.actions.increment()</pre><p>You don’t have to write extra files for action types or action creators like you did in traditional Redux.</p><p>Less code.</p><p>Fewer mistakes.</p><p>Cleaner projects.</p><h3>How Reducers and Actions Work Together</h3><p>Let’s follow a simple flow.</p><p>The user clicks an <strong>Increment</strong> button.</p><p>A component dispatches the increment action.</p><p>Redux sends that action to the reducer.</p><p>The reducer updates the state.</p><p>React automatically re-renders the UI.</p><p>The flow looks like this:</p><pre>Button Click<br>      │<br>      ▼<br>Dispatch Action<br>      │<br>      ▼<br>Reducer Runs<br>      │<br>      ▼<br>State Updates<br>      │<br>      ▼<br>UI Re-renders</pre><p>This predictable flow is one of Redux’s biggest strengths.</p><h3>What is Immer?</h3><p>When beginners first see Redux Toolkit reducers, they often notice something surprising.</p><p>Example:</p><pre>increment(state) {<br>  state.value += 1;<br>}</pre><p>At first glance, it looks like we’re directly modifying the state.</p><p>But wait…</p><p>Didn’t Redux always say <strong>never mutate the state</strong>?</p><p>Yes, it did.</p><p>So why does this code work?</p><p>The answer is <strong>Immer</strong>.</p><p>Immer is a library built into Redux Toolkit.</p><p>It lets you write code that <em>looks</em> like you’re changing the state directly.</p><p>Behind the scenes, Immer creates a copy of the original state, applies your changes to that copy, and returns a brand-new immutable state.</p><p>This gives you simple, readable code while still following Redux’s rule of immutable updates.</p><h3>Why Direct Mutation Appears to Work</h3><p>Without Immer, this would be considered a mutation:</p><pre>state.value += 1;</pre><p>Traditional Redux required code like this:</p><pre>return {<br>  ...state,<br>  value: state.value + 1,<br>};</pre><p>Notice how much more code is required.</p><p>Redux Toolkit hides this complexity.</p><p>When you write:</p><pre>state.value += 1;</pre><p>Immer silently transforms it into an immutable update behind the scenes.</p><p>So you’re <strong>not actually mutating the real Redux state</strong>.</p><p>You’re modifying a temporary “draft” created by Immer, and Immer safely produces a new state object for Redux.</p><p>This is why Redux Toolkit code is both simpler and safer.</p><h3>Creating Your First Slice</h3><p>Now let’s put everything together.</p><p>Create a new file:</p><pre>src<br>└── features<br>    └── counter<br>        └── counterSlice.js</pre><p>Inside that file:</p><pre>import { createSlice } from &quot;@reduxjs/toolkit&quot;;</pre><pre>const initialState = {<br>  value: 0,<br>};</pre><pre>const counterSlice = createSlice({<br>  name: &quot;counter&quot;,<br>  initialState,<br>  reducers: {<br>    increment(state) {<br>      state.value += 1;<br>    },<br>    decrement(state) {<br>      state.value -= 1;<br>    },<br>  },<br>});</pre><pre>export const { increment, decrement } = counterSlice.actions;</pre><pre>export default counterSlice.reducer;</pre><p>Let’s summarize what happens here:</p><ul><li>name identifies the slice.</li><li>initialState defines the starting data.</li><li>reducers describe how the state changes.</li><li>Redux Toolkit automatically creates the action creators.</li><li>counterSlice.reducer is exported so it can be added to the Store.</li><li>increment and decrement actions are exported so components can dispatch them.</li></ul><p>With just a few lines of code, you’ve created everything needed for a feature — something that required much more boilerplate in traditional Redux.</p><h3>Key Takeaways</h3><p>By now, you should understand why slices are the foundation of Redux Toolkit.</p><p>Here’s what we’ve learned:</p><ul><li>A <strong>Slice</strong> represents one feature of your application’s state.</li><li>createSlice() generates reducers, actions, and action types automatically.</li><li>The name property uniquely identifies the slice.</li><li>initialState defines the default data when the application starts.</li><li><strong>Reducers</strong> describe how the state changes.</li><li><strong>Actions</strong> describe what happened and trigger reducers.</li><li><strong>Immer</strong> allows you to write simple update logic while preserving Redux’s immutable state principles.</li><li>Code that looks like direct mutation is actually safe because Immer creates immutable updates behind the scenes.</li></ul><h3>What’s Next?</h3><p>Now that you know how to create slices, it’s time to connect everything together with React.</p><p>In the next article, you’ll learn:</p><ul><li>How to wrap your application with the Provider.</li><li>Why the Provider is necessary.</li><li>How useSelector() reads data from the Store.</li><li>How useDispatch() sends actions to reducers.</li><li>How React components automatically re-render when Redux state changes.</li><li>The complete data flow from a button click to a UI update.</li></ul><p>By the end of the next article, you’ll have your first fully working Redux Toolkit application where React components interact directly with the Redux Store.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2e5627a7ebe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redux Toolkit (Core) — Part 3: Understanding the Redux Store and configureStore() (Complete…]]></title>
            <link>https://medium.com/@wm4012388/redux-toolkit-core-part-3-understanding-the-redux-store-and-configurestore-complete-f4af40cae615?source=rss-111c7c60297c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4af40cae615</guid>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Wali Muhammad]]></dc:creator>
            <pubDate>Thu, 16 Jul 2026 16:39:52 GMT</pubDate>
            <atom:updated>2026-07-16T16:39:52.804Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eYW_CLpMoeNtiucOaJNH4Q.png" /></figure><h3>Redux Toolkit (Core) — Part 3: Understanding the Redux Store and configureStore() (Complete Beginner&#39;s Guide)</h3><p>In the previous article, we installed Redux Toolkit, understood why both @reduxjs/toolkit and react-redux are required, and organized our project using a professional folder structure.</p><p>Now it’s time to build the heart of every Redux application — the <strong>Redux Store</strong>.</p><p>Before writing any code, it’s important to understand one simple fact:</p><blockquote><strong><em>Without a Store, Redux cannot remember or manage your application’s state.</em></strong></blockquote><p>Think of the Store as the brain of your application. Every piece of global data — whether it’s the logged-in user, shopping cart, theme, notifications, or language preference — is stored in one centralized place called the <strong>Store</strong>.</p><p>In this article, we’ll understand what a Store is, how configureStore() creates it, why it replaced the old createStore() method, what middleware does, how Redux DevTools help during development, and how multiple reducers are combined into one Store.</p><h3>What is the Redux Store?</h3><p>A <strong>Store</strong> is the central place where Redux keeps your application’s global state.</p><p>Instead of every component maintaining its own copy of shared data, Redux stores that data in one location.</p><p>This is why Redux is often described as having a <strong>Single Source of Truth</strong>.</p><p>Imagine you’re building an e-commerce application.</p><p>Your application contains:</p><ul><li>Navbar</li><li>Products Page</li><li>Cart Page</li><li>Checkout Page</li><li>Profile Page</li></ul><p>The shopping cart should remain the same on every page.</p><p>Instead of storing the cart separately inside each component, Redux stores it once inside the Store.</p><p>Whenever any component needs the cart, it simply reads it from the Store.</p><pre>Redux Store<br>          -----------------<br>         | Cart            |<br>         | User            |<br>         | Theme           |<br>         | Notifications   |<br>          -----------------<br>          /      |       \<br>      Navbar   Cart   Checkout</pre><p>This keeps the application synchronized because everyone reads from the same source.</p><h3>Why Do We Need a Store?</h3><p>Imagine every department in a company keeps its own employee records.</p><p>Soon you’ll have different versions of the same information.</p><p>One department says an employee has resigned.</p><p>Another still shows them as active.</p><p>A third has an outdated phone number.</p><p>Now imagine one centralized HR database.</p><p>Everyone reads from the same database.</p><p>No duplication.</p><p>No inconsistencies.</p><p>The Redux Store works exactly the same way.</p><p>It ensures that every component always uses the latest state.</p><h3>Creating a Store Using configureStore()</h3><p>Redux Toolkit provides a function called configureStore().</p><p>Its job is to create the application’s Store.</p><p>First, create a folder named <strong>app</strong> inside the src directory.</p><pre>src<br>│<br>└── app<br>     └── store.js</pre><p>Now create store.js.</p><pre>import { configureStore } from &quot;@reduxjs/toolkit&quot;;</pre><pre>export const store = configureStore({<br>  reducer: {},<br>});</pre><p>Let’s understand every line.</p><p>The first line imports configureStore() from Redux Toolkit.</p><pre>import { configureStore } from &quot;@reduxjs/toolkit&quot;;</pre><p>This function creates a Redux Store with sensible defaults, so you don’t have to configure everything manually.</p><p>Next, we create the Store.</p><pre>export const store = configureStore({<br>  reducer: {},<br>});</pre><p>The reducer property tells Redux which reducers will manage different parts of the application&#39;s state.</p><p>Right now it’s empty because we haven’t created any slices yet.</p><p>Later, you’ll register reducers like this:</p><pre>reducer: {<br>  counter: counterReducer,<br>  user: userReducer,<br>}</pre><p>Here, the Store knows that:</p><ul><li>counterReducer manages the counter state.</li><li>userReducer manages the user state.</li></ul><h3>Why is it Called configureStore()?</h3><p>The word <strong>configure</strong> means <strong>to set something up or prepare it</strong>.</p><p>configureStore() doesn&#39;t just create the Store.</p><p>It also configures several important features automatically, such as:</p><ul><li>Redux DevTools</li><li>Middleware</li><li>Better error checking</li><li>Recommended defaults</li><li>Development warnings</li></ul><p>In other words, it prepares the Store for production-quality applications with almost no extra effort.</p><h3>Why Did configureStore() Replace createStore()?</h3><p>Before Redux Toolkit existed, developers created the Store using createStore().</p><p>A simple Store looked something like this:</p><pre>import { createStore } from &quot;redux&quot;;</pre><pre>const store = createStore(rootReducer);</pre><p>This worked, but real-world applications quickly became complicated.</p><p>If you wanted middleware, Redux DevTools, or multiple reducers, you had to configure everything yourself.</p><p>A basic Store often grew into dozens of lines of setup code.</p><p>Redux Toolkit solved this problem.</p><p>Now the same Store can be created much more simply.</p><pre>import { configureStore } from &quot;@reduxjs/toolkit&quot;;</pre><pre>const store = configureStore({<br>  reducer: rootReducer,<br>});</pre><p>Much cleaner.</p><p>Much easier.</p><p>Much safer.</p><p>Today, <strong>configureStore() is the officially recommended way to create a Redux Store</strong>.</p><p>You should avoid using createStore() in new projects because it is considered a legacy API.</p><h3>What is Middleware?</h3><p>Middleware is one of the most confusing concepts for beginners, but the idea is actually simple.</p><p>Imagine you’re sending a package.</p><pre>You<br> ↓<br>Courier Office<br> ↓<br>Destination</pre><p>Before the package reaches its destination, the courier office may:</p><ul><li>Verify the address</li><li>Scan the package</li><li>Record tracking information</li><li>Check for errors</li></ul><p>The package still reaches the destination, but extra work happens in between.</p><p>Redux Middleware works in exactly the same way.</p><pre>Dispatch Action<br>        ↓<br>    Middleware<br>        ↓<br>     Reducer<br>        ↓<br>      Store</pre><p>Whenever an action is dispatched, middleware gets a chance to inspect or modify the process before the reducer updates the state.</p><p>Middleware is commonly used for:</p><ul><li>API requests</li><li>Logging</li><li>Authentication</li><li>Analytics</li><li>Error handling</li><li>Async operations</li></ul><p>The best part is that Redux Toolkit automatically includes useful middleware, so beginners don’t need to configure it manually.</p><h3>What are Redux DevTools?</h3><p>Debugging is one of the biggest challenges in application development.</p><p>Imagine trying to find out:</p><ul><li>Which action changed the cart?</li><li>When did the user log in?</li><li>Why did the state suddenly change?</li></ul><p>Without debugging tools, this becomes difficult.</p><p>Redux DevTools solves this problem.</p><p>It records every action that happens inside your application.</p><p>For example:</p><pre>Action History</pre><pre>LOGIN</pre><pre>ADD_TO_CART</pre><pre>REMOVE_ITEM</pre><pre>CHANGE_THEME</pre><pre>LOGOUT</pre><p>You can click on any action and inspect:</p><ul><li>Previous State</li><li>Current State</li><li>Payload</li><li>Reducer</li><li>Difference between states</li></ul><p>It’s like having a complete history of everything that happened inside your application.</p><p>The best part?</p><p>When using Redux Toolkit, DevTools are automatically enabled during development.</p><p>No extra configuration is required.</p><h3>Combining Multiple Reducers</h3><p>As your application grows, one reducer won’t be enough.</p><p>Imagine your application manages:</p><ul><li>User</li><li>Shopping Cart</li><li>Products</li><li>Theme</li><li>Notifications</li></ul><p>Keeping everything inside one reducer would become difficult.</p><p>Instead, Redux allows us to split responsibilities.</p><p>Example:</p><pre>userReducer</pre><p>Handles:</p><ul><li>Login</li><li>Logout</li><li>Profile</li></ul><p>Another reducer:</p><pre>cartReducer</pre><p>Handles:</p><ul><li>Add Item</li><li>Remove Item</li><li>Update Quantity</li></ul><p>Another:</p><pre>themeReducer</pre><p>Handles:</p><ul><li>Light Mode</li><li>Dark Mode</li></ul><p>Now all of them are registered inside the Store.</p><pre>import { configureStore } from &quot;@reduxjs/toolkit&quot;;</pre><pre>import counterReducer from &quot;../features/counter/counterSlice&quot;;<br>import userReducer from &quot;../features/user/userSlice&quot;;</pre><pre>export const store = configureStore({<br>  reducer: {<br>    counter: counterReducer,<br>    user: userReducer,<br>  },<br>});</pre><p>Let’s understand this object.</p><pre>reducer: {<br>    counter: counterReducer,<br>    user: userReducer,<br>}</pre><p>The key (counter) becomes the name of the state inside the Store.</p><p>So your Store will look something like this:</p><pre>{<br>   counter: {<br>      value: 0<br>   },</pre><pre>   user: {<br>      name: &quot;John&quot;<br>   }<br>}</pre><p>Whenever a component wants the counter value, it reads:</p><pre>state.counter</pre><p>Whenever it wants user information:</p><pre>state.user</pre><p>Each reducer is responsible only for its own part of the Store.</p><p>This separation keeps applications organized and easier to maintain.</p><h3>Putting Everything Together</h3><p>Let’s look at the overall flow.</p><pre>User Clicks Button<br>        │<br>        ▼<br>dispatch(action)<br>        │<br>        ▼<br>Middleware checks the action<br>        │<br>        ▼<br>Reducer updates the state<br>        │<br>        ▼<br>Store saves the latest state<br>        │<br>        ▼<br>React components automatically re-render</pre><p>This predictable flow is one of Redux’s greatest strengths. Every state update follows the same path, making applications easier to understand, debug, and maintain.</p><h3>Key Takeaways</h3><p>By now, you should understand the purpose of the Redux Store and why it is the foundation of every Redux Toolkit application.</p><p>Here’s what we covered:</p><ul><li>A <strong>Store</strong> is the centralized location where Redux keeps global application state.</li><li>configureStore() is the modern and recommended way to create a Store.</li><li>It automatically configures useful defaults such as middleware and Redux DevTools.</li><li>configureStore() replaced the older createStore() API because it reduces boilerplate and follows best practices.</li><li><strong>Middleware</strong> sits between dispatched actions and reducers, allowing extra work such as logging, API calls, and validation.</li><li><strong>Redux DevTools</strong> help developers inspect actions, state changes, and debug applications more effectively.</li><li>Multiple reducers can be combined inside one Store so that each reducer manages only its own piece of state, keeping applications modular and scalable.</li></ul><h3>What’s Next?</h3><p>Now that your Redux Store is ready, it’s time to learn about one of the most powerful features of Redux Toolkit: <strong>Slices</strong>.</p><p>In the next article, you’ll learn:</p><ul><li>What a Slice is.</li><li>Why Redux Toolkit introduced createSlice().</li><li>What initialState represents.</li><li>How reducers are written inside a Slice.</li><li>How actions are automatically generated.</li><li>Why writing code that appears to mutate state is actually safe.</li><li>How Immer works behind the scenes to produce immutable updates with simple syntax.</li></ul><p>By the end of the next article, you’ll build your first working Slice and understand how Redux Toolkit dramatically simplifies state management compared to traditional Redux.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4af40cae615" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>