<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Raju Sarkar</title>
    <description>The latest articles on DEV Community by Raju Sarkar (@rajusarkar).</description>
    <link>https://dev.to/rajusarkar</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1527884%2F18995542-131f-4256-abc4-1fcb8c7b5ce0.jpg</url>
      <title>DEV Community: Raju Sarkar</title>
      <link>https://dev.to/rajusarkar</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/rajusarkar"/>
    <language>en</language>
    <item>
      <title>N+1 query in databases</title>
      <dc:creator>Raju Sarkar</dc:creator>
      <pubDate>Sun, 16 Nov 2025 20:16:04 +0000</pubDate>
      <link>https://dev.to/rajusarkar/n1-query-in-databases-50lb</link>
      <guid>https://dev.to/rajusarkar/n1-query-in-databases-50lb</guid>
      <description>&lt;blockquote&gt;
&lt;h3&gt;
  
  
  Table of content
&lt;/h3&gt;

&lt;p&gt;What is N+1 query&lt;br&gt;
Analogy: The library&lt;br&gt;
Technical example&lt;br&gt;
Inefficient and Efficient query&lt;br&gt;
Why you should care about the N+1 query problem&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  What is N+1 query
&lt;/h2&gt;

&lt;p&gt;The N+1 query problem is a database anti-performance pattern, where an application executes one query to fetch a list of items (N items in 1 query) and then makes N additional individual queries to fetch related data for each item in that list(N number of queries). So, in total you are making 101 queries, 1 query to get the list and 100 query to get names of authors.&lt;/p&gt;

&lt;p&gt;This results in N+1 queries for what should ideally be a single efficient or a few queries.&lt;/p&gt;

&lt;h2&gt;
  
  
  Analogy: The Library
&lt;/h2&gt;

&lt;p&gt;Imagine you go to a library and you ask the librarian to give you a list 100 books of your favorite genre. The librarian gives you the list of 100 books(this is &lt;strong&gt;1 query&lt;/strong&gt;).&lt;/p&gt;

&lt;p&gt;Now you have your list, but you don't know author's name of those 100 books. To know the name of those authors you again go to the librarian and ask him, Hey Librarian can you tell me please what is the name of the author of this book?. You ask this question for each books on that list. In the end guess what, you end up asking the librarian 100 more questions.&lt;/p&gt;

&lt;p&gt;The gist is that you are making &lt;strong&gt;1 query&lt;/strong&gt; to get the list and then you are making &lt;strong&gt;N number of queries&lt;/strong&gt; to get the authors name.&lt;/p&gt;

&lt;h2&gt;
  
  
  Technical Example
&lt;/h2&gt;

&lt;p&gt;Assume that you own a e-commerce platform, where the sellers can list products and users can buy them. In your admin dashboard you want to display all the sellers and their products. There are two tables you have to query &lt;code&gt;1.seller&lt;/code&gt;, &lt;code&gt;2.product&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Let's see both inefficient and efficient ways of querying-
&lt;/h3&gt;

&lt;h4&gt;
  
  
  Inefficient:
&lt;/h4&gt;

&lt;p&gt;Here you first get the sellers by querying the &lt;code&gt;seller&lt;/code&gt; table:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;sellers&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;select&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="k"&gt;from&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;seller&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;And then for each seller you get the products&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;allProducts&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[];&lt;/span&gt;
&lt;span class="k"&gt;for &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;s&lt;/span&gt; &lt;span class="k"&gt;of&lt;/span&gt; &lt;span class="nx"&gt;sellers&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;products&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;db&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;select&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;from&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;product&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;where&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;eq&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;product&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;createdBy&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;s&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;id&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
  &lt;span class="nx"&gt;allProducts&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;push&lt;/span&gt;&lt;span class="p"&gt;(...&lt;/span&gt;&lt;span class="nx"&gt;products&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You are making a api call from your client and then the api do the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;First it query every seller from &lt;code&gt;seller&lt;/code&gt; table&lt;/li&gt;
&lt;li&gt;Then it fetches products for each seller. 
So, if there were 100 seller you will make the first1 query and then 100 more queries in total 101 queries to get what you want.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Efficient:
&lt;/h4&gt;

&lt;p&gt;The efficient version of the above is you tell the &lt;code&gt;db&lt;/code&gt; &lt;strong&gt;hey please give me all the sellers and their products by joining the &lt;code&gt;seller&lt;/code&gt; and &lt;code&gt;product&lt;/code&gt; tables, this way you are going to the &lt;code&gt;db&lt;/code&gt; only once and making a single query.&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;sellersAndProducts&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;db&lt;/span&gt;
  &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;select&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
  &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;from&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;seller&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;innerJoin&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;product&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;eq&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;seller&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;product&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;createdBy&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, instead of fetching products one by one for each seller, you made a single query by joining tables. This one is more simple compare to the first one and also good for database performance.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why you should care about the N+1 query problem?
&lt;/h3&gt;

&lt;p&gt;The answer always will be the performance.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The N+1 query consumes lot lot more resources.&lt;/li&gt;
&lt;li&gt;Lot lot more queries.&lt;/li&gt;
&lt;li&gt;Each individual &lt;code&gt;db&lt;/code&gt; query adds to the overall latency.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If the size of your &lt;code&gt;db&lt;/code&gt; is small you might not face any performance issue but as your &lt;code&gt;db&lt;/code&gt; grows, your user base grows the increased number of queries places a higher load on the database and on the server leading to performance bottleneck.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>postgres</category>
      <category>database</category>
    </item>
    <item>
      <title>React Context APIs, State sharing and Zustand</title>
      <dc:creator>Raju Sarkar</dc:creator>
      <pubDate>Wed, 03 Sep 2025 16:42:15 +0000</pubDate>
      <link>https://dev.to/rajusarkar/react-context-apis-state-sharing-and-zustand-13e6</link>
      <guid>https://dev.to/rajusarkar/react-context-apis-state-sharing-and-zustand-13e6</guid>
      <description>&lt;p&gt;In React, we typically use props to pass data from a parent component to its children component. Props passing works well for small applications, but in larger application, props passing become a pain — especially when data needs to be accessed by deeply nested components.&lt;/p&gt;

&lt;p&gt;Lets imagine a scenario where you have three components — A, B(B is child of A), and C(child of B). If component C needs data from component A, you have to pass that data through B even though B does not actually need it. This makes your development a little bit complex and also, you have to compromise with the performance.&lt;/p&gt;

&lt;p&gt;To solve this problem, React provides the Context API, which allows you to share values across different component, without having to pass props manually at every level.&lt;/p&gt;

&lt;h2&gt;
  
  
  Get started with Context API
&lt;/h2&gt;

&lt;p&gt;Create a empty React project&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm create vite@latest
// Select React
// Then select typescript
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After this, create two folder inside the src — context and components.&lt;/p&gt;

&lt;p&gt;Lets setup the context first.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//ThemeContext.tsx

import { createContext, useContext, useState, type ReactNode } from "react";

// theme context with default theme value `light`
// and a empty callback function to change theme
const ThemeContext = createContext({ theme: "light", toggle: () =&amp;gt; {} });

// this is our theme provider
export const ThemeProvider = ({ children }: { children: ReactNode }) =&amp;gt; {
  // state variables for theme
  const [theme, setTheme] = useState("light");

  // theme toggle function
  const toggle = () =&amp;gt;
    setTheme((prev) =&amp;gt; (prev === "light" ? "dark" : "light"));

  return (
    // wraping the children with context provider
    // and providing valus
    &amp;lt;ThemeContext.Provider value={{ theme, toggle }}&amp;gt;
      {children}
    &amp;lt;/ThemeContext.Provider&amp;gt;
  );
};
// export the useTheme, so it can be consumed by components
export const useTheme = () =&amp;gt; useContext(ThemeContext);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code we are importing — createContext, useContext, useState and type ReactNode from React.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;import { createContext, useContext, useState, type ReactNode } from "react";&lt;br&gt;
&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;At first we need to initiate a context, So we are initiating ThemeContext with a default value light and a callback function, toggle to change the theme value, this will create a context that components can read from or update values of that context.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// theme context with default theme value
// and a empty callback function to change theme
const ThemeContext = createContext({ theme: "light", toggle: () =&amp;gt; {} });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we need a context provider, for that we are creating ThemeProvider, this is the component that will wrap a child component and give access to data, values to that child component.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// this is our theme provider
export const ThemeProvider = ({ children }: { children: ReactNode }) =&amp;gt; {
  // state variables for theme
  const [theme, setTheme] = useState("light");

  // theme toggle function
  const toggle = () =&amp;gt;
    setTheme((prev) =&amp;gt; (prev === "light" ? "dark" : "light"));

  return (
    // wraping the children with context provider
    // and providing valus
    &amp;lt;ThemeContext.Provider value={{ theme, toggle }}&amp;gt;
      {children}
    &amp;lt;/ThemeContext.Provider&amp;gt;
  );
};

export const useTheme = () =&amp;gt; useContext(ThemeContext);

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

&lt;/div&gt;



&lt;p&gt;In the above code we are wrapping the children with our ThemeContext that we have created before.&lt;/p&gt;

&lt;p&gt;And at last we are exporting the useTheme, so components can access the ThemeContext value without wrapping them by ThemeProvider.&lt;/p&gt;

&lt;p&gt;Now lets actually use the ThemeProvider in our App.tsx. First lets create a component, ThemeSwitch.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// ThemeSwitch.tsx

// import the useTheme from our theme context
import { useTheme } from "../context/ThemeContext";

export default function ThemeSwitch() {
  // initiate
  const { theme, toggle } = useTheme();

  return (
    &amp;lt;div className="p-2"&amp;gt;
      {/* on button click this will call the `toggle` function 
        and changes the theme */}
      &amp;lt;button onClick={toggle} className="border p-2 bg-amber-100 rounded"&amp;gt;
        Theme switch
      &amp;lt;/button&amp;gt;

      &amp;lt;p className="text-4xl"&amp;gt;
        Current theme: &amp;lt;span className="underline text-blue-600"&amp;gt;{theme}&amp;lt;/span&amp;gt;
      &amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we are importing the useTheme from our ThemeContext. Inside our ThemeSwitch initiate the useTheme(), and here we can get access of theme and toggle. On button click this triggers the toggle function that we have in our ThemeConntext and changes the theme.&lt;/p&gt;

&lt;p&gt;Now in our App.tsx, clear all the boilerplate code, import the ThemeProvider and wrap the ThemeSwitch with that.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// App.tsx

// get the theme provider from theme context
import { ThemeProvider } from "./context/ThemeContext";
// get the theme switch component
import ThemeSwitch from "./components/ThemeSwitch";


const App = () =&amp;gt; {
  return (
    &amp;lt;ThemeProvider&amp;gt;
      &amp;lt;ThemeSwitch /&amp;gt;
    &amp;lt;/ThemeProvider&amp;gt;
  );
};

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now run the code and you can see on clicking the button it changes the theme.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fd5bmhh501w6iv2ohbkwg.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fd5bmhh501w6iv2ohbkwg.gif" alt="Changing color on button click" width="800" height="518"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To demonstrate this further lets create another component, DemonstrateThemeChange.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// DemonstrateThemeChange.tsx

import { useTheme } from "../context/ThemeContext";

export default function DemonstrateThemeChange() {
  const { theme } = useTheme();

  return (
    &amp;lt;div className="p-2"&amp;gt;
      &amp;lt;div
        className={`h-48 w-48 rounded flex justify-center items-center ${
          theme === "light" ? "bg-gray-300" : "bg-black text-white"
        }`}
      &amp;gt;
        &amp;lt;p&amp;gt;{theme}&amp;lt;/p&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffwg80vwbhfpakqs4m0uh.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffwg80vwbhfpakqs4m0uh.gif" alt="Component box color change" width="1292" height="838"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here we are importing the useTheme and rendering css according to current theme. Now if you click the ThemeSwitch button you will see that the the DemonstrateThemeChange box color changes without any wrapping. This way you can eliminate props drilling&lt;/p&gt;

&lt;p&gt;So, is Context API enough to manage states and share data across an React application? The answer is no.&lt;br&gt;
Context API is great for smaller application to store one or two states, but when the application gets bigger we need a better approach, a better solution to manage states across our application.&lt;/p&gt;

&lt;p&gt;Why Context is not recommended for large scale applications :&lt;br&gt;
Re-Renders all consumers: Lets say, that you have context user, that stores user profile info and also user shopping cart details, now if that user add a new item to their cart, user’s shopping cart data will get updated, and this will trigger re-render for both shopping cart data consumer and user profile data consumer.&lt;br&gt;
No built in selector: You can not subscribe to only one part of a context, like I want only user profile data not the shopping cart data. To do this you have split the context which adds complexity.&lt;br&gt;
Provider hell: To deal with above problems, lets say that you have separated your context, but now guess what you have to do deep nesting.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;UserProvider&amp;gt;
  &amp;lt;ThemeProvider&amp;gt;
    &amp;lt;CartProvider&amp;gt;
      &amp;lt;App /&amp;gt;  // 🤯 Too many wrappers!
    &amp;lt;/CartProvider&amp;gt;
  &amp;lt;/ThemeProvider&amp;gt;
&amp;lt;/UserProvider&amp;gt;

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

&lt;/div&gt;



&lt;p&gt;To solve this we have dedicated state management tools like Redux/Zustand.&lt;br&gt;
By using state management tools like Redux/Zustand you can avoid Unnecessary re-render, provider hello and you can also get built-in optimization.&lt;/p&gt;
&lt;h2&gt;
  
  
  Get Started with Zustand
&lt;/h2&gt;

&lt;p&gt;Zustand is a small, fast, and scalable state management solution.&lt;/p&gt;

&lt;p&gt;To use Zustand you have to install it:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm install zustand&lt;br&gt;
&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;After installation create a store folder in the src of your project directory and inside that store folder create a useUserStore.ts. Inside our user store file paste:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { create } from "zustand";
import { persist } from "zustand/middleware";

const useUserStore = create(persist((set) =&amp;gt; ({}), {name: "user-store"}))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we are importing create from zustand to create the store, and then we are importing the persist to enable state persistence. You can create a zustand store without using persist, but in that case, the state will be lost when the page is refreshed. The third line is the boilerplate code for creating a zustand store.&lt;/p&gt;

&lt;p&gt;If you prefer JS, your are good to go — you can now declare the states inside this useUserStore. Because I am using TS, I will first create a type interface and then use that interface in my store.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { create } from "zustand";
import { persist } from "zustand/middleware";

// TYPE INTERFACE FOR SHOPPING CART
interface UserShoppingCart {
    productName: string,
    productPrice: string,
    productQty: number
}

// TYPE INTERFACE FOR USER
interface User {
    isLoading: boolean,
    isError: boolean,
    errorMessage: string | null

    // TO STORE VALUE
    isUserLogedIn: boolean,
    userShoppingCart: UserShoppingCart[]

    // FUNCTIONS TO CHANGE VALUE
    changeUserLogedInStatus: ({isLogedIn}:{isLogedIn: boolean}) =&amp;gt; void
    addItemToUserShoppingCart: ({productName, productPrice, productQty} : {productName: string, productPrice: string, productQty: number}) =&amp;gt; void
}

// OUR STORE
const useUserStore = create(persist&amp;lt;User&amp;gt;((set) =&amp;gt; ({
    // PROVIDING THE STATE VARIABLE TO OUR STORE
    isLoading: false,
    isError: false,
    errorMessage: null,

    isUserLogedIn: false,
    userShoppingCart: [],

    changeUserLogedInStatus : ({isLogedIn}) =&amp;gt; {},
    addItemToUserShoppingCart: ({productName, productPrice, productQty}) =&amp;gt; {},
}), {name: "user-store"}))

// EXPORT THE STORE 
export { useUserStore }

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

&lt;/div&gt;



&lt;p&gt;So, above I introduced two type interface, User and UserShoppingCart. These ensures type safety for our state data across different components. After that we provide the state variable to our store with initial values.&lt;/p&gt;

&lt;p&gt;Here you can declare as many state variables as you need, like —userSessionId or userShoppingHistory or anything else you need.&lt;/p&gt;

&lt;p&gt;Now lets see how we can change value or update value in our store. Lets create two basic components, LoginButton and AddToCartButton — These will be just a normal button, whenever we click this buttons values into our store will get updated. The AddToCartButton will only shown to the user when the isUserLogedIn value is true.&lt;/p&gt;

&lt;p&gt;So, lets first complete our store functions which will update our state value&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const useUserStore = create(persist&amp;lt;User&amp;gt;((set) =&amp;gt; ({
    isLoading: false,
    isError: false,
    errorMessage: null,

    isUserLogedIn: false,
    userShoppingCart: [],

    changeUserLogedInStatus : ({isLogedIn}) =&amp;gt; {
        set({isUserLogedIn: isLogedIn})
    },
    addItemToUserShoppingCart: ({productName, productPrice, productQty}) =&amp;gt; {
        set((prev) =&amp;gt; ({
            userShoppingCart: [...prev.userShoppingCart, {productName, productPrice, productQty}]
        }))
    },
}), {name: "user-store"}))

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

&lt;/div&gt;



&lt;p&gt;To update our store with new value we need use the set property. Those two functions are simple JS code, If you find it difficult to understand to can Google them.&lt;/p&gt;

&lt;p&gt;Now lets create our component to update user login status.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useUserStore } from "../store/useUserStore"

export default function LoginButton(){
    const {changeUserLogedInStatus, isUserLogedIn} = useUserStore()
    return (
        &amp;lt;div className="flex justify-center items-center min-h-[20vh]"&amp;gt;
            &amp;lt;button className="border bg-gray-300 active:bg-gray-400"
            onClick={() =&amp;gt; {
                changeUserLogedInStatus({isLogedIn: !isUserLogedIn})
            }}
            &amp;gt;Update login status&amp;lt;/button&amp;gt;
        &amp;lt;/div&amp;gt;
    )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I have created a LoginButton component in my component folder and there I have imported the changeUserLogedInStatus and isUserLogedIn(current user login status) from useUserStore and then I am updating the user login status to opposite of current value on button click.&lt;/p&gt;

&lt;p&gt;Now remove everything from App.tsx return statement and add the below code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import LoginButton from "./components/LoginButton";

const App = () =&amp;gt; {
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;LoginButton /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now go to localhost of your app and then your browser’s local storage section then click on the Update login status button and now you will see a new store added to your local storage with the updated userLogedIn status.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fk0kvdb7gz3z3833ipd7d.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fk0kvdb7gz3z3833ipd7d.gif" alt="Zustand store in browser" width="752" height="796"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcml3vcya1d3kz3t9a7n6.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcml3vcya1d3kz3t9a7n6.gif" alt="Zustand store in browser" width="752" height="796"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now lets create the AddToCartButton component.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useUserStore } from "../store/useUserStore"

export default function AddToCartButton(){
    const {addItemToUserShoppingCart} = useUserStore()
    return (
        &amp;lt;div className="flex justify-center items-center min-h-[30vh]"&amp;gt;
            &amp;lt;button
             className="border bg-blue-300 active:bg-blue-400"
             onClick={() =&amp;gt; {
                addItemToUserShoppingCart({productName: "Ferrari Roma", productPrice: "4 CR", productQty: 1})
             }}
            &amp;gt;Add to cart&amp;lt;/button&amp;gt;
        &amp;lt;/div&amp;gt;
    )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Create the component in component folder and import the addItemToUserShoppingCart and then add the logic for adding items to shopping cart on button click. But we want this button to be visible only when the user is logged In. To do that we will update our App.tsx.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import AddToCartButton from "./components/AddToCartButton";
import LoginButton from "./components/LoginButton";
import { useUserStore } from "./store/useUserStore";

const App = () =&amp;gt; {
  const {isUserLogedIn}=  useUserStore()
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;LoginButton /&amp;gt;

      {
        isUserLogedIn &amp;amp;&amp;amp; (&amp;lt;AddToCartButton /&amp;gt;)
      }
    &amp;lt;/div&amp;gt;
  );
};

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we are rendering the AddToCartButton only when the user login status is true. Now if you click the Add to cart button this will add item to your shopping cart.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9u00npwk7ovykm11k1k9.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9u00npwk7ovykm11k1k9.gif" alt="Change store value on button click" width="760" height="571"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwzgv9g7gw0gferdmdozu.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwzgv9g7gw0gferdmdozu.gif" alt="Change store value on button click" width="760" height="571"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;At the begging the user login status is false and when we click on the login button the status updated as true, now we can see the add to cart button. On clicking the add to cart button this will add the provided item into the shopping cart.&lt;/p&gt;

&lt;p&gt;So this is how you can manage states store data and access them across different component using Zustand.&lt;/p&gt;

&lt;p&gt;To learn more about Zustand you can refer to Zustand official &lt;a href="https://zustand.docs.pmnd.rs/getting-started/introduction" rel="noopener noreferrer"&gt;docs&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Source code is available on &lt;a href="https://github.com/rajusrkr/react-context-api-and-zustand" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt;. Also you can provide your feedback on &lt;a href="https://x.com/rajusrkr" rel="noopener noreferrer"&gt;Twitter/X&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>react</category>
      <category>javascript</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
