<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Quincy Oghenetejiri Ukumakube - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Quincy Oghenetejiri Ukumakube - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Wed, 10 Jun 2026 23:15:56 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/Quincy-Oghenetejiri/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Use the App Directory in Next.js ]]>
                </title>
                <description>
                    <![CDATA[ When you're building a project using the latest version of Next.js, you'll be prompted to select between using the app/ directory or the pages/ directory. The app/ directory is now the recommended way of building apps in Next.js. In this article, you... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/app-directory-nextjs/</link>
                <guid isPermaLink="false">66ba2f4bd8f1b6513f67389e</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Next.js ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Quincy Oghenetejiri Ukumakube ]]>
                </dc:creator>
                <pubDate>Thu, 15 Feb 2024 00:52:55 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/Freecodecamp-Banner-2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When you're building a project using the latest version of Next.js, you'll be prompted to select between using the <code>app/</code> directory or the <code>pages/</code> directory. The <code>app/</code> directory is now the recommended way of building apps in Next.js.</p>
<p>In this article, you'll learn how to maximize the potential of the <code>app</code> directory in Next.js by learning about its available features.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-the-app-folder">The <code>app/</code> Folder</a></li>
<li><a class="post-section-overview" href="#heading-layout">Layout</a> </li>
<li><a class="post-section-overview" href="#heading-routing">Routing</a> </li>
<li><a class="post-section-overview" href="#heading-fonts-usage">Fonts usage</a></li>
<li><a class="post-section-overview" href="#heading-the-loadingjsx-file">Loading Component</a> </li>
<li><a class="post-section-overview" href="#heading-the-errorjsx-file">Error Component</a> </li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/p/eef6be7d-0a78-4259-8106-3994bb8268c1/the-not-found-jsx-file">Not-Found Component</a></li>
<li><a class="post-section-overview" href="#heading-the-templatejsx-file">Template Component</a></li>
<li><a class="post-section-overview" href="#heading-server-components">Server Component</a></li>
</ul>
<h2 id="heading-the-app-folder">The <code>app/</code> Folder</h2>
<p>The <code>app/</code> directory in Next.js comes with a lot of features, unlike the <code>pages/</code> directory. Some of these features include:  </p>
<ul>
<li>Layout</li>
<li>Routing </li>
<li>Fonts usage</li>
<li>Loading Component</li>
<li>Error Component </li>
<li>Not Found Component</li>
<li>Template Component</li>
<li>Server Component</li>
</ul>
<h3 id="heading-layout">Layout</h3>
<p>Using <code>Layout</code> in thte <code>app/</code> directory makes it simpler to lay down complex interfaces that enable advanced routing patterns, prevent costly re-renders, and maintain state across navigations.</p>
<p>In the <code>app/</code> directory, you can utilize the <code>Layout</code> function by creating a <code>layout.jsx</code> file at the root of the <code>app/</code> directory. This defines a user interface (UI) that is shared across multiple locations. </p>
<p>A layout can render another layout or a page within it. Whenever a route changes to any component within the layout, its state is preserved because the layout component does not unmount.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Layout-Screenshot-.png" alt="Image" width="600" height="400" loading="lazy">
<em>An image showing a nested layout in the app directory</em></p>
<h4 id="heading-how-to-add-meta-tags-to-layouts">How to add meta tags to Layouts</h4>
<p>Meta tags are small pieces of information that provide details about a webpage to browsers and search engines. </p>
<p>To add meta tags to your application when using the <code>app/</code> directory in Next.js, you can use metadata in the <code>layout.js</code> file. The metadata is exported from the file, similar to the following code snippet:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> metadata = {
  <span class="hljs-attr">title</span>: <span class="hljs-string">'Keyword Title'</span>,
  <span class="hljs-attr">description</span>: <span class="hljs-string">'Any Keyword,Another Keyword, More Keywords '</span>,
};
</code></pre>
<p>Overriding the meta tag of the main layout is crucial when you want to have different meta tags for each route. To override these, you need to export the variable <code>metadata</code> from the route file where you want the meta tag to take effect.</p>
<h4 id="heading-theres-no-appjs-file">There's no <code>_app.js</code> file</h4>
<p>The <code>_app.jsx</code> file has disappeared from the <code>app/</code> directory. As you may have anticipated, we will store everything under the <code>layout.jsx</code> file, which is the basic layout when using the <code>app/</code> directory in Next.js.</p>
<p>If, for instance, you want to use Chakra UI, you will need to place the provider in the <code>layout.jsx</code> file. Below is a code snippet from the Chakra documentation demonstrating how to link the provider to the layout file:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// app/providers.tsx</span>
<span class="hljs-string">'use client'</span>

<span class="hljs-keyword">import</span> { ChakraProvider } <span class="hljs-keyword">from</span> <span class="hljs-string">'@chakra-ui/react'</span>

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Providers</span>(<span class="hljs-params">{ children }: { children: React.ReactNode }</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ChakraProvider</span>&gt;</span>{children}<span class="hljs-tag">&lt;/<span class="hljs-name">ChakraProvider</span>&gt;</span></span>
}
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">// app/layout.tsx</span>
<span class="hljs-keyword">import</span> { Providers } <span class="hljs-keyword">from</span> <span class="hljs-string">'./providers'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">RootLayout</span>(<span class="hljs-params">{
  children,
}: {
  children: React.ReactNode,
}</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">'en'</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Providers</span>&gt;</span>{children}<span class="hljs-tag">&lt;/<span class="hljs-name">Providers</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span></span>
  )
}
</code></pre>
<h3 id="heading-routing">Routing</h3>
<p>Routing in the <code>app/</code> directory involves the use of strictly folder-based routing. This is unlike the <code>pages/</code> directory, which allows the use of either file-based routing or folder-based routing.</p>
<p>Folder-based routing involves creating a folder where the name of the route should match the name of the folder, and then creating a <code>page.js</code> file which references the <code>/</code> URL of that folder. </p>
<p>For instance, if you create a folder called <code>about</code>, and a <code>page.js</code> is created in that folder, assuming you are still using a development server, the URL will be <code>localhost:3000/about</code>. Similarly, any folder created anywhere in the <code>app/</code> directory will follow this pattern.</p>
<h4 id="heading-nested-routing">Nested routing</h4>
<p>Nested routes in the <code>app/</code> directory involve creating or nesting folders within others. Since each folder in the <code>app/</code> directory corresponds to a route, with the <code>page.js</code> file in the respective folder pointing to the <code>/</code> URL of that folder, you can create nested routes by placing folders within other folders.</p>
<p>For example, the <code>/dashboard/analytics</code> URL path would correspond to a folder structure like <code>app/dashboard/analytics</code>, with a <code>page.js</code> file present in the <code>analytics</code> folder to make the route publicly accessible.</p>
<h4 id="heading-route-group">Route group</h4>
<p>Due to the folder-based approach of the app directory, each folder containing a <code>page.js</code> file is automatically considered a route for that application. </p>
<p>To avoid using the folder name directly in the route, you can enclose the folder name in parentheses, such as <code>(name_of_folder)</code>, which effectively groups the routes under that name. You can see this visually represented in the image below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Pictures-Showing-the-routing-done-in-next-14.png" alt="Image" width="600" height="400" loading="lazy">
<em>Image Illustrating Route Group</em></p>
<h3 id="heading-fonts-usage">Fonts Usage</h3>
<p>In Next.js 12, installing fonts in the <code>page/</code> directory involves copying the font stylesheet link into the CSS file. </p>
<p>But in Next.js 13, the process in the <code>app/</code> directory involves using the <code>import</code> keyword to import any font of your choice from <code>next/font/google</code>. After importing, the subset of the font is initialized and stored in a variable which is then added to the body tag as a class. </p>
<pre><code class="lang-javascript"><span class="hljs-comment">//importing the fonts </span>
<span class="hljs-keyword">import</span> { Inter } <span class="hljs-keyword">from</span> <span class="hljs-string">'next/font/google'</span>;

<span class="hljs-comment">//initialising a variable </span>
<span class="hljs-keyword">const</span> inter = Inter({ <span class="hljs-attr">subsets</span>: [<span class="hljs-string">'latin'</span>] });



<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">RootLayout</span>(<span class="hljs-params">{ children }</span>) </span>{


  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
        //Adding the variable as a class to the body tag
        <span class="hljs-tag">&lt;<span class="hljs-name">body</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{inter.className}</span>&gt;</span>
            {children}
        <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
}
</code></pre>
<h4 id="heading-how-to-create-a-favicon">How to create a favicon</h4>
<p>Similarly, the way we import fonts in Next.js has evolved since its introduction, and so has the method for creating a favicon. </p>
<p>In the <code>app/</code> directory, creating a favicon in Next.js involves either creating or replacing the <code>favicon.ico</code> file located in the root folder of the app directory with the image you wish to use. Note that if your image is in another format, such as JPG, PNG, or SVG, you need to convert it to ICO format.</p>
<h3 id="heading-the-loadingjsx-file">The <code>loading.jsx</code> file.</h3>
<p>Utilizing a loading component is a useful feature in Next.js, where you can obtain the loading function simply by creating a file named <code>loading.jsx</code> in the designated folder. This is particularly useful when you are fetching data from an API and need to display a loading state while awaiting the response. </p>
<p>You can create a <code>loading.jsx</code> file that sets its state to 'loading' while waiting for the API response.</p>
<p>Here's an example of what a <code>loading.jsx</code> file might look like:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// app/loading.jsx </span>
<span class="hljs-keyword">const</span> loadingPage = <span class="hljs-function">()=&gt;</span>{
    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"loader"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"loader-wrapper"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"loader"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"/img/Spinner-1s-120px.gif"</span>/&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"loader-section section-left"</span>&gt;</span>

                <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"loader-section section-right"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>


      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>

    )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> loadingPage
</code></pre>
<h3 id="heading-the-errorjsx-file">The <code>error.jsx</code> file.</h3>
<p>The <code>error.jsx</code> file is a special file used to handle server-side errors. It is part of the new error handling features introduced in Next.js version 13.4. </p>
<p>This file is intended to replace the traditional <code>pages/error.js</code> or <code>pages/_error.js</code> files for handling errors in a more centralized manner. </p>
<p>One main advantage is that this file can handle both client-side and server-side errors. It can receive a <code>statusCode</code> prop to determine the type of error that occurred and display the appropriate message or style.</p>
<p>Below is an example of what an <code>error.jsx</code> file could look like:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// app/error.jsx</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Error</span>(<span class="hljs-params">{ statusCode }</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Error<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>An error {statusCode} occurred on server<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-built_in">Error</span>.getInitialProps = <span class="hljs-function">(<span class="hljs-params">{ res, err }</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> statusCode = res ? res.statusCode : err ? err.statusCode :  <span class="hljs-number">404</span>;
  <span class="hljs-keyword">return</span> { statusCode };
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-built_in">Error</span>;
</code></pre>
<p>In the example above, the <code>Error</code> component receives a <code>statusCode</code> prop, which is determined in the <code>getInitialProps</code> method. This method checks if there is a response object (<code>res</code>), an error object (<code>err</code>), or defaults to <code>404</code> if neither is present. The status code is then displayed in the error page.</p>
<h3 id="heading-the-not-foundjsx-file"><strong>The <code>not-found.jsx</code> file</strong></h3>
<p>The <code>not-found.jsx</code> file is a special file convention used to handle cases where a user navigates to a route that doesn't exist within that application. It is typically used to render a custom "Not Found" page when a requested resource cannot be found</p>
<p>Here's an example of what a <code>not-found.jsx</code> could look like:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// app/not-found.jsx</span>
<span class="hljs-keyword">import</span> Link <span class="hljs-keyword">from</span> <span class="hljs-string">'next/link'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">NotFound</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Not Found<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>The page you were looking for does not exist.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/"</span>&gt;</span>Go back home<span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<h3 id="heading-the-templatejsx-file">The <code>template.jsx</code> file.</h3>
<p>Imagine you have a box of LEGO blocks, and you want to build different types of cars. A <code>template.jsx</code> file in Next.js is like a special blueprint that helps you build those cars. Each car has a different design, but they all follow the same basic rules of building.</p>
<p>The <code>template.jsx</code> file tells Next.js how to put together the pieces for each page of your website. Just like how you might use a simple blueprint to build many cars, the <code>template.jsx</code> file gives instructions for building many web pages.</p>
<p>Every time you want to make a new page, you would follow the blueprint. But unlike a normal blueprint, this one gets wiped clean after you finish making a page, so you start fresh with a new page. This is why it's called a "template" – it's something you use as a starting point for building something else.</p>
<p>Sometimes, you might want to add a special feature to just one car, like a glow-in-the-dark bumper. In Next.js, you could do this with a <code>template.jsx</code> file by adding a special piece of code just for that one page. After you finish, you'll forget about the special feature because the blueprint gets erased.</p>
<p>So, in short, a <code>template.jsx</code> file is like a special rule book that helps you make different pages on your website, and it starts fresh for each new page you make.</p>
<h4 id="heading-how-is-it-different-from-layoutjsx-file">How is it different from layout.jsx file?</h4>
<p>In Next.js, both <code>template.jsx</code> and <code>layout.jsx</code> are used to wrap around pages and provide a common structure, but they behave differently when it comes to navigation and state preservation.</p>
<p><strong>Layouts (<code>layout.jsx</code>)</strong>: These are persistent and maintain their state across different routes. They are ideal for elements that should stay the same and consistent throughout the navigation, such as headers, footers, and sidebars. </p>
<p>Layouts minimize re-renders and help boost performance since they don't re-mount and re-render upon navigation.</p>
<p><strong>Templates (<code>template.jsx</code>)</strong>: These are not persistent and create a new instance for each of their children on navigation. This means that when a user navigates between routes that share a template, a new instance of the component is mounted, DOM elements are recreated, and state is not preserved. </p>
<p>Templates are useful when you need to isolate components from sharing state or behaviors, or when you need to trigger certain effects or state changes every time a user navigates to a component. </p>
<p>For example, they are suitable for collecting feedback with a <code>useState</code> managed form that's unique to each page or tracking page views with <code>useEffect</code>.</p>
<p>In essence, layouts are for consistent, stateful elements, while templates are for distinct, state-independent components that need fresh state on each navigation. You would choose layouts for efficiency and consistency, and templates for isolated, state-independent components that require fresh state on navigation.</p>
<h3 id="heading-server-components">Server Components</h3>
<p>Server components are now the default state of the app directory in Next.js . They allow you to perform server-side rendering in your front-end application, which reduces the amount of JavaScript code sent to the client.</p>
<p>Some of the benefits of using server components include:</p>
<ul>
<li>Data fetching</li>
<li>Security</li>
<li>Caching</li>
<li>Bundle Sizes</li>
<li>Search Engine Optimization and Social Network Shareability</li>
</ul>
<h4 id="heading-server-side-rendering-ssr-vs-server-components-in-nextjs">Server side rendering (SSR) vs server components in Nextjs</h4>
<p>The key differences between these two lie in where they are used (pages vs. app), how they affect the client-side bundle size, and the level of control they provide over rendering. </p>
<p>Server Components offer a way to leverage server-side logic without the overhead of traditional SSR, which can lead to better performance and maintainability for modern web applications.</p>
<p>Also, while both SSR and Server Components render on the server, the latter does not support interactivity—a process known as hydration—with JS, and as such, event handlers and React features such as useState, useEffect, and other DOM operations do not function with it. </p>
<p>You can gain access to these features by converting the default server component into a client component by placing the <code>useClient</code> directive at the top of the code.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The <code>app/</code> directory in Next.js offers a robust set of features designed to enhance the developer experience and optimize the performance of applications. </p>
<p>By leveraging the <code>app/</code> directory, you can take full advantage of the latest advancements in Next.js, such as the <code>Layout</code> component for managing UI consistency and state preservation, folder-based routing for streamlined navigation, and the ability to import fonts and create favicons with ease.</p>
<p>The introduction of special files like <code>loading.jsx</code>, <code>error.jsx</code>, and <code>not-found.jsx</code> provides a centralized approach to handling loading states, errors, and non-existent routes, respectively. </p>
<p>Also, the <code>template.jsx</code> file acts as a blueprint for constructing web pages, offering flexibility for unique page designs while ensuring a consistent structure. </p>
<p>Server components, now the default in the <code>app/</code> directory, also offer significant benefits</p>
<p>At this point you are confident enough to utilize this features in building powerful, scalable, and maintainable applications with Next.js.</p>
<p>### </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Redux Toolkit to Manage State in Your React Application ]]>
                </title>
                <description>
                    <![CDATA[ State management is one of the most important things you'll deal with in front end development.  You can manage state in React in various ways. Some examples include using state in class components, using React hooks such as useState and useEffect ho... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/use-redux-toolkit-to-manage-state-in-react-apps/</link>
                <guid isPermaLink="false">66ba2f4d54ccc2d852dc891a</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ State Management  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Quincy Oghenetejiri Ukumakube ]]>
                </dc:creator>
                <pubDate>Mon, 24 Apr 2023 21:38:24 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/Freecodecamp-Banner.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>State management is one of the most important things you'll deal with in front end development. </p>
<p>You can manage state in React in various ways. Some examples include using state in class components, using React hooks such as useState and useEffect hook, using the Context API, or using Redux. </p>
<p>In this article I will show you how to use the Redux toolkit for state management in React. </p>
<h3 id="heading-prerequisites">Prerequisites</h3>
<ul>
<li>Basic knowledge of React (beginners are welcome) and JavaScript is required.</li>
<li>Have Node installed so you can download the package using <code>npm</code>.</li>
</ul>
<h2 id="heading-what-is-redux-toolkit">What is Redux toolkit?</h2>
<p>Redux Toolkit is a set of tools you can use for state management in React in place of Redux. The Redux team created it. </p>
<p>Redux Toolkit offers a standardized approach to building Redux code and comes with libraries and tools that make it simpler to create scalable, maintainable, and effective Redux code.</p>
<h3 id="heading-how-is-it-different-from-the-old-redux">How is it different from the old Redux?</h3>
<p>Redux toolkit is different from Redux in a few ways. First, it has less boilerplate code, and it has decent support. It also works best with functional components (unlike Redux which works best with class components).</p>
<p>There are various reasons why you should use Redux toolkit over Redux for state management: </p>
<ol>
<li>Less boilerplate code than Redux.</li>
<li>You don't have to set up thunk manually in Redux toolkit as it comes with <code>createAsyncThunk</code>. This enables you to perform async operations.</li>
<li>Enhancing developer experience: Redux Toolkit includes a number of tools and utilities that can enhance the developer experience, such as the ability to use Redux DevTools out-of-the-box.</li>
<li>Redux hooks like useSelector and useDispatch make your code shorter and easier to read/write.</li>
<li>Improving performance: Redux Toolkit includes a built-in memoization feature that can help improve the performance of your Redux application by reducing unnecessary re-renders.</li>
</ol>
<p>In summary, Redux Toolkit is a great choice for developers who want to simplify their Redux code and improve performance, while also enhancing the developer experience. It can be particularly useful in larger, more complex applications where managing state can become difficult.</p>
<h2 id="heading-how-to-get-started-with-redux-toolkit">How to Get Started with Redux Toolkit</h2>
<p>For this project, you won't use <code>create-react-app</code> to create your React app. Instead, you'll use Vite and React plugins. This is because CRA is no longer recommended by the React docs.</p>
<p>To create your app, run the code below in your terminal:</p>
<pre><code>npm create vite@latest my-app --template react
</code></pre><p>Next, run the following commands in the terminal:</p>
<pre><code>cd my-app
npm install
npm run dev
</code></pre><h3 id="heading-how-to-install-redux-toolkit">How to install Redux Toolkit</h3>
<p>To make use of Redux Toolkit in your project, run the code below in your terminal:</p>
<pre><code>npm install @reduxjs/toolkit react-redux
</code></pre><h3 id="heading-how-to-create-a-redux-store">How to create a Redux store</h3>
<p>After the installation is complete, create a file named <code>src/redux/store.jsx</code> . Import <code>configureStore</code> from Redux Toolkit and then create an empty Redux store which will be exported like you can see in the code below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { configureStore } <span class="hljs-keyword">from</span> <span class="hljs-string">'@reduxjs/toolkit'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> store = configureStore({
  <span class="hljs-attr">reducer</span>: {},
})
</code></pre>
<p>This code creates a Redux store, and also automatically configures the Redux DevTools extension so that you can inspect the store while developing.</p>
<h3 id="heading-how-to-connect-the-redux-store-to-react">How to connect the Redux Store to React</h3>
<p>After you've created the store, you will have to wrap your <code>&lt;App/&gt;</code> with a <code>&lt;Provider/&gt;</code> which will be imported from react-redux. Also the store you created above will be passed in into the provider as a prop.</p>
<pre><code class="lang-js"><span class="hljs-comment">//main.js</span>
<span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom'</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'./index.css'</span>
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">'./App'</span>
<span class="hljs-comment">//Importing the store we created above</span>
<span class="hljs-keyword">import</span> { store } <span class="hljs-keyword">from</span> <span class="hljs-string">"./redux/store"</span>
<span class="hljs-comment">//importing the provider from react-redux  </span>
<span class="hljs-keyword">import</span> { Provider } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-redux'</span>

ReactDOM.render(
    <span class="hljs-comment">//This makes the store accessible to the App that is passing it as a prop</span>
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Provider</span> <span class="hljs-attr">store</span>=<span class="hljs-string">{store}</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">Provider</span>&gt;</span></span>,
  <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'root'</span>)
)
</code></pre>
<h3 id="heading-how-to-create-a-redux-state-slice">How to create a Redux state slice</h3>
<p>After the store has been created, create a file <code>src/redux/countslice.jsx</code>. Then import <code>createSlice</code> from <code>@redux/toolkit</code>.</p>
<p>A Redux slice is a concept introduced by Redux Toolkit that represents a self-contained piece of the Redux store that includes a reducer function, initial state, and action creators.</p>
<p>Slices provide a way to organize and modularize Redux code, making it easier to manage and maintain as your application grows. You can think of slices as mini-Redux stores that handle a specific piece of state within your application.</p>
<p>Creating a slice requires three things:</p>
<ul>
<li>Name, which is usually set to be a string. </li>
<li>Initial State Value.</li>
<li>Reducer, which contains actions that define how the state can be updated.</li>
</ul>
<p>Creating a state slice creates a more modular and maintainable architecture for your application, making it easier to reason about and update as your application grows.</p>
<p>By organizing your Redux code into slices, you can create a more modular and maintainable architecture for your application, making it easier to reason about and update as your application grows.</p>
<p>After you create the slice, the reducers and the Redux actions inside the reducers are exported differently. This is because the slice created will need to be exported before it can be used inside the store. </p>
<p>By exporting the reducer from the slice, you can easily use it to configure your Redux store. It also makes it easy to test the reducer in isolation, without needing to set up a full Redux store. This can be useful for unit testing and ensuring that the reducer behaves as expected for each action it handles.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { createSlice } <span class="hljs-keyword">from</span> <span class="hljs-string">'@reduxjs/toolkit'</span>

<span class="hljs-keyword">const</span> initialState = {
  <span class="hljs-attr">count</span>: <span class="hljs-number">0</span>,
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> counterSlice = createSlice({
  <span class="hljs-attr">name</span>: <span class="hljs-string">'counter'</span>,
  initialState,
  <span class="hljs-attr">reducers</span>: {
    <span class="hljs-attr">increment</span>: <span class="hljs-function">(<span class="hljs-params">state</span>) =&gt;</span> {
      state.count += <span class="hljs-number">1</span>
    },
    <span class="hljs-attr">decrement</span>: <span class="hljs-function">(<span class="hljs-params">state</span>) =&gt;</span> {
      state.count -= <span class="hljs-number">1</span>
    },
    <span class="hljs-attr">incrementByAmount</span>: <span class="hljs-function">(<span class="hljs-params">state, action</span>) =&gt;</span> {
      state.count += action.payload
    },
  },
})

<span class="hljs-comment">// Action creators are generated for each case reducer function</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> { increment, decrement, incrementByAmount } = counterSlice.actions

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> counterSlice.reducer
</code></pre>
<h3 id="heading-how-to-add-the-slice-to-the-store">How to add the slice to the store</h3>
<p>The <code>Reducer</code> exported from the slice is imported and added to the store you created earlier. This allows you to complete the configuration of the store.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//store.jsx</span>
<span class="hljs-keyword">import</span> { configureStore } <span class="hljs-keyword">from</span> <span class="hljs-string">'@reduxjs/toolkit'</span>
<span class="hljs-comment">//Importing the reducer from countSlice</span>
<span class="hljs-keyword">import</span> counterReducer <span class="hljs-keyword">from</span> <span class="hljs-string">"./countslice"</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> store = configureStore({
  <span class="hljs-attr">reducer</span>: {
    <span class="hljs-attr">counter</span>: counterReducer,
  },
})
</code></pre>
<h3 id="heading-how-to-use-the-state-and-actions-in-your-react-components">How to use the state and actions in your React components.</h3>
<p>Up until now, you've just been going through the initial set up for Redux Toolkit, setting up the store and creating the reducer. Now you need to start making use of the state and actions in your app to achieve the desired functionality.</p>
<p>You will be using two hooks: <code>useDispatch</code> and <code>useSelector</code> . Data are being read from the store through the <code>useSelector</code> hook while the actions are being dispatched using the <code>useDispatch</code> hook. </p>
<p>The corresponding actions (increment, decrement, and incrementByAmount) are being imported from the <code>countSlice.jsx</code> file to be used by the <code>dispatch</code>.</p>
<p>Take a look at the code below where the state is set to a variable <code>count</code> using the <code>useSelector</code> hook and the actions is set to a variable <code>dispatch</code> using the <code>useDispatch</code>. There are three buttons: the <code>increase</code> button, <code>decrease</code> button, and <code>increaseByAmount</code> button. An <code>onClick</code> event was placed on each button which run the various action.</p>
<p>When these buttons are clicked, two things happens:</p>
<ul>
<li>The Redux action is dispatched to the store.</li>
<li>The slice reducer will see the action and then update the state.</li>
</ul>
<p>Here's the code that does all that:</p>
<pre><code class="lang-js"><span class="hljs-comment">//App.jsx</span>
<span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> { useSelector, useDispatch } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-redux'</span>
<span class="hljs-keyword">import</span> { decrement, increment, incrementByAmount } <span class="hljs-keyword">from</span> <span class="hljs-string">"./redux/countslice"</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> count = useSelector(<span class="hljs-function">(<span class="hljs-params">state</span>) =&gt;</span> state.counter.count)
  <span class="hljs-keyword">const</span> dispatch = useDispatch()

  <span class="hljs-keyword">return</span> (

      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'App'</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>The count is {count}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"button"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
          <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> dispatch(increment())}
        &gt;
          Increase
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
          <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> dispatch(decrement())}
        &gt;
          Decrease
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span>=&gt;</span>dispatch(incrementByAmount(10))} &gt; Increase by 10<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>

        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>

  )
}
</code></pre>
<h3 id="heading-the-result">The Result</h3>
<p>This is exactly what you should get when you run your code:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/Redux-toolkit-GIF.gif" alt="Image" width="600" height="400" loading="lazy">
<em>App Showing the function of Redux Toolkit</em></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This tutorial walked you through how you can make use of Redux toolkit in handling your state in React. You learned how to create a store using various hooks such as the  useSelector and useDispatch hook to read data from the store. </p>
<p>At this point you should be confident enough to use the Redux toolkit for managing state in your React app. </p>
<p>Let’s connect on <a target="_blank" href="https://twitter.com/Quincyoghenex">Twitter</a> and <a target="_blank" href="https://www.linkedin.com/in/quincy-oghenetejiri">LinkedIn</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
