<?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[ React context - 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[ React context - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 26 Jul 2026 04:13:56 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/react-context/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Use React's Context API – Tutorial with Examples ]]>
                </title>
                <description>
                    <![CDATA[ In React, data is typically passed down from parent to child via props. But this can lead to "prop drilling" – where we have to pass props down through lots of components to get them where they're needed. Also, some props (for example, the current au... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-context-api-tutorial-examples/</link>
                <guid isPermaLink="false">66c8c99f85ffc69fd028a82c</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React context ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Danny ]]>
                </dc:creator>
                <pubDate>Mon, 22 Jul 2024 15:25:40 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/07/React.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In React, data is typically passed down from parent to child via props. But this can lead to "prop drilling" – where we have to pass props down through lots of components to get them where they're needed.</p>
<p>Also, some props (for example, the current authenticated user, UI theme, or preferred language) will be required by many components within an application.</p>
<p>React's Context API provides a way to share values like these between components without having to explicitly pass them down as a prop through every level of the tree. So, Context is designed to share data that can be considered "global" for a tree of React components.</p>
<h2 id="heading-what-youll-learn-in-this-article">What You'll Learn in This Article</h2>
<ul>
<li><a class="post-section-overview" href="#heading-what-is-the-react-context-api-and-when-should-you-use-it">What is the React Context API and when should you use it?</a></li>
<li><a class="post-section-overview" href="#heading-react-context-api-example-light-and-dark-mode-ui-theme">React Context API example: how to switch between light and dark mode UI themes</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-multiple-react-contexts">How to create multiple React Contexts (and why you should)</a></li>
<li><a class="post-section-overview" href="#heading-how-to-prevent-the-react-context-re-render-issue">How to prevent the React Context re-render issue</a></li>
<li><a class="post-section-overview" href="#heading-react-context-api-vs-redux">React Context API vs Redux for global state management</a></li>
</ul>
<h2 id="heading-source-code">Source Code</h2>
<p>All examples from this article are in this repo: https://github.com/DoableDanny/React-context-API-tutorial</p>
<p>I also made a video version of this article to make it easier for you to follow along with the examples: <a target="_blank" href="https://www.youtube.com/watch?v=hkGiP6Ur-B4">React Context Tutorial with Examples
</a></p>
<h2 id="heading-what-is-the-react-context-api-and-when-should-you-use-it">What is the React Context API and When Should You Use It?</h2>
<p>The Context API is a feature in React that provides a way to share values like themes, user information, or configuration settings between components without having to explicitly pass props through every level of the component tree. This makes it particularly useful for managing global state, or state that is needed by many components at different nesting levels.</p>
<p>The Context API is a part of the React library, meaning that you don't need to install it as a third-party package in a React application.</p>
<p>So, the Context API can be used for sharing global variables between components in a React app, without having to pass these variables as props down the component tree. This is especially useful if there are components that are deeply nested that need access to variables from higher up components.</p>
<p>Now, let's learn how the Context API works by going through a common use case example for the Context API...</p>
<h2 id="heading-react-context-api-example-light-and-dark-mode-ui-theme">React Context API Example — Light and Dark Mode UI Theme</h2>
<p>A very common real-world usecase for the React Context API is for storing the current user's prefered theme – that is, "light mode" or "dark mode".</p>
<p>Think about it: many of the UI components in a React app will need to know about the current theme, in order to display the approprate styles. Buttons, Headings, the Navbar, the Footer, Dropdowns – lots of components are going to need to display themselves differently depending on the current theme.</p>
<h3 id="heading-the-passing-down-a-prop-solution">The passing-down-a-prop solution</h3>
<p>The most simple and obvious "React" way to solve this would be to create a <code>theme</code> variable in the main top-level <code>App</code> component, and then keep on passing it down as a prop to all of the components in the tree. But this leads to a React problem known as "prop drilling".</p>
<p>Prop drilling is a term used in React to describe the process of passing data from a parent component to a deeply nested child component through multiple intermediary components. This can happen when you need to pass state or functions several levels down the component tree.</p>
<p>Prop drilling example:</p>
<pre><code class="lang-jsx">
<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> theme = <span class="hljs-string">'dark'</span>;
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Parent</span> <span class="hljs-attr">theme</span>=<span class="hljs-string">{theme}</span> /&gt;</span></span>;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Parent</span>(<span class="hljs-params">{ theme }</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Child</span> <span class="hljs-attr">theme</span>=<span class="hljs-string">{theme}</span> /&gt;</span></span>;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Child</span>(<span class="hljs-params">{ theme }</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Button</span> <span class="hljs-attr">theme</span>=<span class="hljs-string">{theme}</span> /&gt;</span></span>;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Button</span>(<span class="hljs-params">{ theme }</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">background:</span> <span class="hljs-attr">theme</span> === <span class="hljs-string">'dark'</span> ? '<span class="hljs-attr">black</span>' <span class="hljs-attr">:</span> '<span class="hljs-attr">white</span>' }}&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>;
}
</code></pre>
<p>As you can see, each intermediary component needs to include the prop, even if it doesn't use it, just to pass it down further. This clutters the code and makes it more difficult to understand. </p>
<p>Also, intermediary components that do not use the props might still re-render when the props change, leading to performance issues. This can be particularly problematic in large applications with deep component trees.</p>
<h3 id="heading-context-api-to-the-rescue">Context API To The Rescue</h3>
<p>We can solve this prop drilling issue by using the Context API.</p>
<h4 id="heading-creating-a-context">Creating a context</h4>
<p>First, we need to create the context, and pass in the light theme as the default value:</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// src/contexts/ThemeContext.js</span>

<span class="hljs-keyword">import</span> { createContext } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> themes = {
  <span class="hljs-attr">light</span>: {
    <span class="hljs-attr">background</span>: <span class="hljs-string">"white"</span>,
    <span class="hljs-attr">text</span>: <span class="hljs-string">"black"</span>,
  },
  <span class="hljs-attr">dark</span>: {
    <span class="hljs-attr">background</span>: <span class="hljs-string">"black"</span>,
    <span class="hljs-attr">text</span>: <span class="hljs-string">"white"</span>,
  },
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> ThemeContext = createContext(themes.light);
</code></pre>
<p>Above, we have created a <code>contexts</code> folder inside of our <code>src</code> folder for storing all of our contexts. It's considered good practice to create each context in its own file. In our case, we just need to create a context for storing the current theme.</p>
<p>Notice that contexts are created by calling the <code>createContext()</code> function that comes from the <code>React</code> library. We pass the <code>createContext()</code> function a default value of <code>themes.light</code>.</p>
<h4 id="heading-providing-a-context">Providing a context</h4>
<p>Next, we need to wrap all of the components that need access to the theme in a context provider. The context provider takes a <code>value</code> prop, where we can pass the value that we want to make global. </p>
<p>Below, <code>&lt;Navbar /&gt;</code> and <code>&lt;Button /&gt;</code> will have access to the <code>theme</code> state, even though we haven't explicitly passed it down as a prop. This is because we have wrapped these components in the theme context provider, and passed it the value (<code>theme</code>) that needs to be made global.</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// src/App.js</span>

<span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>
<span class="hljs-keyword">import</span> { ThemeContext, themes } <span class="hljs-keyword">from</span> <span class="hljs-string">"./contexts/ThemeContext"</span>
<span class="hljs-keyword">import</span> Navbar <span class="hljs-keyword">from</span> <span class="hljs-string">"./components/Navbar"</span>
<span class="hljs-keyword">import</span> Button <span class="hljs-keyword">from</span> <span class="hljs-string">"./components/Button"</span>

<span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [theme, setTheme] = useState(themes.light)

  <span class="hljs-keyword">const</span> toggleTheme = <span class="hljs-function">() =&gt;</span> {
    setTheme(<span class="hljs-function"><span class="hljs-params">state</span> =&gt;</span> (state === themes.light ? themes.dark : themes.light))
  }

  <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">ThemeContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{theme}</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Navbar</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Button</span> <span class="hljs-attr">changeTheme</span>=<span class="hljs-string">{toggleTheme}</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">ThemeContext.Provider</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> App
</code></pre>
<p>If we also wanted to make <code>setTheme()</code> available throughout our app via context, we could pass the following object to the <code>value</code> prop. We'd then be able to toggle the theme from any component within the Theme Context Provider:</p>
<pre><code class="lang-jsx">&lt;ThemeContext.Provider value={{ theme, setTheme }}&gt;
</code></pre>
<p>Now let's create the <code>Button</code> and <code>Navbar</code> components that will consume the theme context using the <code>useContext()</code> hook. Notice how the CSS styles of the components change depending on the current theme values:</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// src/components/Button.js</span>

<span class="hljs-keyword">import</span> React, { useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>
<span class="hljs-keyword">import</span> { ThemeContext } <span class="hljs-keyword">from</span> <span class="hljs-string">"../contexts/themeContext"</span>

<span class="hljs-keyword">const</span> Button = <span class="hljs-function">(<span class="hljs-params">{ changeTheme }</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> theme = useContext(ThemeContext)

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>
      <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">backgroundColor:</span> <span class="hljs-attr">theme.background</span>, <span class="hljs-attr">color:</span> <span class="hljs-attr">theme.text</span> }}
      <span class="hljs-attr">onClick</span>=<span class="hljs-string">{changeTheme}</span>
    &gt;</span>
      Toggle theme
    <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Button
</code></pre>
<pre><code class="lang-jsx"><span class="hljs-comment">// src/components/Navbar.js</span>

<span class="hljs-keyword">import</span> React, { useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>
<span class="hljs-keyword">import</span> { ThemeContext } <span class="hljs-keyword">from</span> <span class="hljs-string">"../contexts/themeContext"</span>

<span class="hljs-keyword">const</span> Navbar = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> theme = useContext(ThemeContext)

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">nav</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">backgroundColor:</span> <span class="hljs-attr">theme.background</span> }}&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">color:</span> <span class="hljs-attr">theme.text</span> }}&gt;</span>Home<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">color:</span> <span class="hljs-attr">theme.text</span> }}&gt;</span>About<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">nav</span>&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Navbar
</code></pre>
<p><strong>Here are the steps involved in using a context</strong>:</p>
<ol>
<li>Import the context that you want to use (<code>ThemeContext</code> in this example) into the component. </li>
<li>Import the <code>useContext</code> hook from <code>React</code>.</li>
<li>Inside of the component that needs access to the context value(s), call the <code>useContext</code> hook and pass the context that you want to use. Assign this to a variable (<code>const theme = useContext(ThemeContext)</code> in our example)</li>
<li>The component now has access to the global variable, and the component will re-render/be updated every time a value inside of the context is updated.</li>
</ol>
<p>OK, that's everything that we need for this example. Let's now start up our application by running the following command in the project route:</p>
<p><code>npm run start</code></p>
<p>Now let's test things out in the browser.</p>
<p>Light mode:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/03/light_mode.JPG" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em><strong> Press the Toggle Theme button </strong></em></p>
<p>Dark mode:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/03/dark_mode.JPG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>And there we go, we've used the context API to share the theme state throughout our application – without having to pass it down as a prop. Cool! 👌</p>
<h2 id="heading-how-to-create-multiple-react-contexts">How to Create Multiple React Contexts</h2>
<p>In our example above, we only created one context, <code>ThemeContext</code>. But what if we had other data that needed to be made global, such as the current logged in user's <code>username</code> and <code>age</code>?</p>
<p>We could just create one big context for storing all variables that needed to be consumed globally:</p>
<pre><code class="lang-jsx">&lt;OneBigContext.Provider value={{ theme, username, age }}&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Button</span> <span class="hljs-attr">changeTheme</span>=<span class="hljs-string">{toggleTheme}</span> /&gt;</span></span>
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Navbar</span> /&gt;</span></span>
&lt;/OneBigContext.Provider&gt;
</code></pre>
<p>But this is considered bad practice, as whenever a context value is updated, all components consuming that context will be re-rendered. This means that all components that only need to know about the <code>theme</code>, and not the user variables, will get re-rendered whenever any of the user variables are updated. This can worsen an app's performance, especially in larger apps with lots of complex components.</p>
<p>We can solve this by creating multiple contexts – one context for the theme and another for the user data – and wrapping our app in both providers, like so:</p>
<pre><code class="lang-jsx">&lt;ThemeContext.Provider value={theme}&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">UserContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">username</span>, <span class="hljs-attr">age</span> }}&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">Button</span> <span class="hljs-attr">changeTheme</span>=<span class="hljs-string">{toggleTheme}</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">Navbar</span> /&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">UserContext.Provider</span>&gt;</span></span>
&lt;/ThemeContext.Provider&gt;
</code></pre>
<p>By only storing related data in each context, we help prevent unnecessary re-renders of components, and improve the performance of our app.</p>
<h2 id="heading-how-to-prevent-the-react-context-re-render-issue">How to Prevent the React Context Re-render Issue</h2>
<p>As we've discussed, whenever a context value is updated, all components consuming that context will be rerendered – even if wrapped in <code>React.memo()</code>. (If you don't know what <code>React.memo()</code> is, don't panic – we'll discuss it soon!) This can worsen an app’s performance. </p>
<p>But we can mitigate this problem with the following methods:</p>
<h3 id="heading-1-use-multiple-react-contexts">1. Use Multiple React Contexts</h3>
<p>This is what we discussed above, and is the "preferred" way of solving the rerender problem (<a target="_blank" href="https://github.com/facebook/react/issues/15156#issuecomment-474590693">see this answer</a>).</p>
<h3 id="heading-2-split-the-component-and-pass-the-needed-value">2. Split the Component and Pass the Needed Value</h3>
<p>You can also split the component up and pass down (as a prop) the needed value from context, with the child components wrapped in <code>React.memo()</code>. Example:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> Card = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> appContextValue = useContext(AppContext);
  <span class="hljs-keyword">const</span> theme = appContextValue.theme;

  <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">CardTitle</span> <span class="hljs-attr">theme</span>=<span class="hljs-string">{theme}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">CardDescription</span> <span class="hljs-attr">theme</span>=<span class="hljs-string">{theme}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">const</span> CardTitle = React.memo(<span class="hljs-function">(<span class="hljs-params">{ theme }</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h2</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">color:</span> <span class="hljs-attr">theme.text</span> }}&gt;</span>This is the Title <span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span></span>;
});

<span class="hljs-keyword">const</span> CardDescription = React.memo(<span class="hljs-function">(<span class="hljs-params">{ theme }</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">color:</span> <span class="hljs-attr">theme.text</span> }}&gt;</span>lorem ipsum dolor sit amet,<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;
});
</code></pre>
<p><code>React.memo()</code> is a higher-order component (HOC) in React that is used to optimize functional components by preventing unnecessary re-renders. It does this by memoizing the component, meaning it will only re-render if its props change.</p>
<ul>
<li>Without <code>React.memo()</code>: The components, <code>CardTitle</code> and <code>CardDescription</code>, would re-render whenever their parent, <code>Card</code>, re-renders – even if their props haven't changed. This can lead to performance issues in larger applications or with components that are expensive to render.</li>
<li>With <code>React.memo()</code>: <code>CardTitle</code> and <code>CardDescription</code> only re-render if their props change, reducing unnecessary renders and improving performance.</li>
</ul>
<p>So, by splitting the component up, passing down only the values that are needed as props, and wrapping the components in <code>React.memo()</code>, <code>CardTitle</code> and <code>CardDescription</code> will only be re-rendered if <code>theme</code> is updated, but not if <code>username</code> is updated. </p>
<p>This solution is particularly useful if we can’t split out context for whatever reason.</p>
<h3 id="heading-3-one-component-with-reactusememo-inside">3. One Component with <code>React.useMemo()</code> Inside</h3>
<p>Below, <code>theme</code> is a dependency of <code>useMemo()</code>, so we will only get a re-render of the elements returned by the callback function when <code>theme</code> is changed:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> Card = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> appContextValue = useContext(AppContext);
  <span class="hljs-keyword">const</span> theme = appContextValue.theme;

  <span class="hljs-keyword">return</span> useMemo(
    <span class="hljs-function">() =&gt;</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">CardTitle</span> <span class="hljs-attr">theme</span>=<span class="hljs-string">{theme}</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">CardDescription</span> <span class="hljs-attr">theme</span>=<span class="hljs-string">{theme}</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    ),
    [theme]
  );
};

<span class="hljs-keyword">const</span> CardTitle = <span class="hljs-function">(<span class="hljs-params">{ theme }</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h2</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">color:</span> <span class="hljs-attr">theme.text</span> }}&gt;</span>This is the Title <span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span></span>;
};

<span class="hljs-keyword">const</span> CardDescription = <span class="hljs-function">(<span class="hljs-params">{ theme }</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">color:</span> <span class="hljs-attr">theme.text</span> }}&gt;</span>lorem ipsum dolor sit amet,<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;
};
</code></pre>
<p>Here's how <code>useMemo()</code> works:</p>
<ol>
<li>The first parameter of <code>useMemo()</code> is a callback function that returns a memoized value. In this case, it returns a React element, or tree of React elements.</li>
<li>The second parameter is an array of dependences. If any of the values in this dependency array are updated, then the callback function provided as the first argument is called, and the elements that the callback function returns are re-rendered.</li>
</ol>
<p>So, <code>useMemo()</code> can be used to only re-render React elements if certain values specified in the dependency array are updated.</p>
<p>By wrapping these elements in <code>useMemo()</code>, and specifying <code>theme</code> as the only dependency, the elements only get re-rendered if <code>theme</code> is updated, but won't get re-rendered if any other context value is updated.</p>
<p>This solution is also particularly useful if we can’t split out context.</p>
<h2 id="heading-react-context-api-vs-redux">React Context API vs Redux</h2>
<p>This is a very common and much-depated topic within the React community. React Context API and Redux are both tools for managing state in a React application, but they have different use cases, strengths, and limitations. </p>
<p>The Context API is a built-in feature of React, with the primary purpose of allowing state to be shared across a tree of React components without prop drilling.</p>
<p>The Context API has a simple API: <code>React.createContext()</code>, <code>Provider</code>, and the <code>useContext()</code> hook. And is good for small to medium-sized apps, as it is straightforward to use, and requires little setup and boilerplate code.</p>
<p>On the other hand, Redux is a state management library that has to be installed as a third-party package into an application. Its primary purpose is to manage application-wide state in a predictable way, especially in large and complex applications.</p>
<h4 id="heading-why-context-api-is-good-for-small-to-medium-sized-apps">Why Context API is good for small-to-medium-sized apps:</h4>
<ul>
<li><strong>Simplicity</strong>: It's simpler than Redux.</li>
<li><strong>Built-in</strong>: It's part of React, so no need to install extra packages, making maintenance of the project easier.</li>
<li><strong>Minimal boilerplate</strong>: Requires less boilerplate and setup than Redux.</li>
</ul>
<h4 id="heading-why-redux-is-good-for-larger-more-complex-applications">Why Redux is good for larger, more complex applications:</h4>
<ul>
<li><strong>Single Store</strong>: Maintains a single store for the entire application state, which makes debugging and testing easier.</li>
<li><strong>Predictable State Updates</strong>: Uses pure functions (reducers) to manage state updates, ensuring predictability and immutability.</li>
<li><strong>Middleware Support</strong>: Powerful middleware system (like redux-thunk or redux-saga) for handling asynchronous actions and side effects.</li>
<li><strong>DevTools Integration</strong>: Excellent developer tools for time-travel debugging and state inspection.</li>
<li><strong>Suitable for Large Apps</strong>: Designed to handle complex state logic and large-scale applications.</li>
</ul>
<p><strong>Redux maintainer, <a target="_blank" href="https://x.com/acemarke?lang=en">Mark Erikson</a>, gives the following reasons for using Redux</strong>:</p>
<ul>
<li>Consistent architectural patterns</li>
<li>Debugging capabilities</li>
<li>Middleware</li>
<li>Addons and extensibility</li>
<li>Cross-platform and cross-framework usage</li>
<li>Depending on your app's setup, much better performance than working with just Context (we don't have to worry about the rerender problem we get with Context, mentioned above – components only rerender when the value they are using updates)</li>
</ul>
<h4 id="heading-in-summary">In summary:</h4>
<ul>
<li>Redux is a more complex state management tool that provides more features and tools. It provides a consistent way of managing state throughout an application, which is very helpful on larger projects with multiple developers (as they won't all be implementing their own styles of state management and making the codebase inconsistent).</li>
<li>React Context API is more straightforward, requires less setup, and is a good solution for smaller to medium sized projects where the added complexity and overhead of using a tool like Redux isn't necessary.</li>
</ul>
<h2 id="heading-thank-you-for-reading">Thank you for reading!</h2>
<p>If you found this article useful, you can hear more from me by:</p>
<ul>
<li><a target="_blank" href="https://www.youtube.com/channel/UC0URylW_U4i26wN231yRqvA">Subscribing to my YouTube channel</a>. I plan to turn it into a React/NextJS/Node-focused channel, with in-depth videos 😎.</li>
<li><a target="_blank" href="https://twitter.com/doabledanny">Following me on Twitter</a> where I tweet about my freelancing journey, side projects and current learnings.</li>
<li><a target="_blank" href="https://www.doabledanny.com/blog/">Checking out my tech blog</a></li>
</ul>
<h3 id="heading-free-react-hooks-course">Free React Hooks Course</h3>
<p>Want to learn all the hooks in React? I created a free 2 hour video explaining all 9 core React Hooks with examples: <a target="_blank" href="https://www.youtube.com/watch?v=TXN6HYGLba4&amp;ab_channel=DoableDanny">React Hooks Tutorial — All React Hooks Explained with Examples</a>. If you enjoy, consider subscribing to <a target="_blank" href="https://www.youtube.com/channel/UC0URylW_U4i26wN231yRqvA">my channel</a>.</p>
<p>Cheers!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use React Context in Your Project – Beginner's Guide ]]>
                </title>
                <description>
                    <![CDATA[ As beginners, managing state in React applications can be challenging, especially when passing and utilizing props in deeply nested components.  The usual way of passing information from a main component to its smaller parts — like a parent passing d... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-react-context/</link>
                <guid isPermaLink="false">66bb9055a5fd14123a8b4a20</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React context ]]>
                    </category>
                
                    <category>
                        <![CDATA[ State Management  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Benedicta Onyebuchi ]]>
                </dc:creator>
                <pubDate>Fri, 05 Jan 2024 20:06:06 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/Learn-With-Benedicta.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>As beginners, managing state in React applications can be challenging, especially when passing and utilizing props in deeply nested components. </p>
<p>The usual way of passing information from a main component to its smaller parts — like a parent passing data to a child, then to a grandchild — can get complicated and tiring, especially when we need to access something deep down in the hierarchy.</p>
<p>In this article, we'll explore how the React Context API works, its use cases and a sample project utilizing the concept.</p>
<h2 id="heading-what-is-react-context">What is React Context?</h2>
<p>React Context provides us a way to pass data down through the component tree to where we need it without having to manually pass props at every single level. </p>
<p>It acts as a global storage space for all your components in your project.</p>
<h2 id="heading-how-is-react-context-different-from-prop-threading">How is React Context Different from Prop Threading?</h2>
<p>In prop threading<strong>,</strong> data is passed down from the parent component to the child component. If a child of that component needs the same prop, it is passed down until the required component gets the data. </p>
<p>While simple, it can become complex when traversing deeply nested structures, and this results in prop drilling.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/context-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>A pictural representation of prop threading</em></p>
<p>In contrast, React Context allows data to be passed from the parent component to any nested component that requires it, simplifying the process. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-02-114317.png" alt="Image" width="600" height="400" loading="lazy">
<em>A representation of React context.</em></p>
<h2 id="heading-what-is-prop-drilling">What is Prop Drilling?</h2>
<p>Prop drilling refers to a situation where this threading of props becomes complicated due to the need to pass them through multiple layers of components. </p>
<p>As the data is passed down through many layers, each intermediate component needs to receive and pass the data, even if it doesn't use the data itself.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// App.js</span>

<span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> GrandchildComponent = <span class="hljs-function">(<span class="hljs-params">{ dataFromChild }</span>) =&gt;</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">p</span>&gt;</span>Username in Grandchild: {dataFromChild.username}<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-keyword">const</span> ChildComponent = <span class="hljs-function">(<span class="hljs-params">{ dataFromParent }</span>) =&gt;</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">p</span>&gt;</span>Your email: {dataFromParent.email}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">GrandchildComponent</span> <span class="hljs-attr">dataFromChild</span>=<span class="hljs-string">{dataFromParent}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">const</span> ParentComponent = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [userData, setUserData] = useState({
    <span class="hljs-attr">username</span>: <span class="hljs-string">'benny_dicta'</span>,
    <span class="hljs-attr">email</span>: <span class="hljs-string">'benedictaonyebuchi@gmail.com'</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>Welcome, {userData.username}!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">ChildComponent</span> <span class="hljs-attr">dataFromParent</span>=<span class="hljs-string">{userData}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ParentComponent</span> /&gt;</span></span>;
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>The code above shows a typical case of prop drilling where data is passed from the <code>ParentComponent</code> to the <code>GrandChild</code> component even when they are not needed by that component.</p>
<ul>
<li><code>ParentComponent</code> is the top-level component that holds some data (<code>userData</code>).</li>
<li><code>ChildComponent</code> is a child of <code>ParentComponent</code> and receives <code>dataFromParent</code> as a prop. It also renders a <code>GrandChildComponent</code>, passing the received prop further down.</li>
<li><code>GrandChildComponent</code> is deeply nested and receives the prop <code>dataFromChild</code>. It renders the data in its UI.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-02-115808.png" alt="Image" width="600" height="400" loading="lazy">
<em>A representation of a simple project structure</em></p>
<h2 id="heading-when-to-choose-react-context">When to choose React Context</h2>
<ul>
<li>For simple and straightforward projects, prop threading would be adequate.</li>
<li>For complex projects requiring data to traverse multiple nested layers, React Context provides a cleaner solution.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-02-120902.png" alt="Image" width="600" height="400" loading="lazy">
<em>A representation of a deeply nested application</em></p>
<p>The pictural difference between both approaches can be seen here. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-02-124809.png" alt="Image" width="600" height="400" loading="lazy">
<em>A pictural representation of the difference between react context and prop drilling.</em></p>
<h2 id="heading-what-are-the-use-cases-for-react-context-api">What are the Use Cases for React Context API?</h2>
<p>Here are some of the use cases for React Context:</p>
<ol>
<li>When prop drilling becomes complicated: Imagine having to pass a prop through multiple layers of components just to reach the one that needs it. Context API eliminates this prop-drilling headache.</li>
<li>Global data requirement: When multiple components need access to the same data (for example: user authentication status, theme preferences, and so on), using context makes it accessible without redundant prop passing.</li>
<li>Themable components: If your application requires changing themes, like light and dark modes, and you want components deep in the tree to adapt dynamically to theme changes, Context API makes this seamless.</li>
<li>Multi-level nesting: In deeply nested component trees, passing props down the hierarchy becomes impractical. Context provides a cleaner solution for sharing data across various levels.</li>
</ol>
<h2 id="heading-how-to-use-react-context-api">How to use React Context API</h2>
<h4 id="heading-step-1-create-a-context">Step #1 - Create a Context</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { createContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> MyContext = createContext();
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> MyContext;
</code></pre>
<h4 id="heading-step-2-wrap-your-app-with-context-provider">Step #2 - Wrap your App with Context Provider</h4>
<pre><code class="lang-javascript"><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> MyContext <span class="hljs-keyword">from</span> <span class="hljs-string">'./MyContext'</span>;

<span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> sharedValue = <span class="hljs-string">'This is a shared value'</span>;

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">MyContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{sharedValue}</span>&gt;</span>
      {/* Your components go here */}
    <span class="hljs-tag">&lt;/<span class="hljs-name">MyContext.Provider</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<h4 id="heading-step-3-consume-the-context-in-components">Step #3 - Consume the Context in Components</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> MyContext <span class="hljs-keyword">from</span> <span class="hljs-string">'./MyContext'</span>;

<span class="hljs-keyword">const</span> MyComponent = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> sharedValue = useContext(MyContext);

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{sharedValue}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> MyComponent;
</code></pre>
<h2 id="heading-the-three-important-parts-of-the-react-context-api">The three Important Parts of the React Context API.</h2>
<p>In this section, we'll talk about the three important parts of the React Context API: Provide, Context, and Consumer.</p>
<h3 id="heading-provider">Provider</h3>
<p>This is a component that is used to wrap components in order to access to the context's value. This is where you pass the values that you want to share throughout the component tree using the <code>value</code> prop. </p>
<pre><code class="lang-javascript"><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> MyContext <span class="hljs-keyword">from</span> <span class="hljs-string">'./MyContext'</span>;

<span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> sharedValue = <span class="hljs-string">'This is a shared value'</span>;

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">MyContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{sharedValue}</span>&gt;</span>
     {children} {/*all components in its subtree*/}
    <span class="hljs-tag">&lt;/<span class="hljs-name">MyContext.Provider</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>In the code above, the context is imported and the <code>.Provider</code> appended to the context, <code>MyContext</code>. This makes the prop passed to the Provider available to all of its children. That is, the components in its subtree.</p>
<h3 id="heading-context">Context</h3>
<p>This acts as the storage where the data is stored. It comes with two parts:</p>
<ul>
<li><code>createContext()</code> — This creates the global object and creates the context.</li>
<li><code>useContext()</code> — This consumes the information made available by the provider.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-comment">/*MyComponent.js*/</span>

<span class="hljs-keyword">import</span> React, { createContext, useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> MyContext = createContext();

<span class="hljs-keyword">const</span> MyComponent = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> sharedValue = useContext(MyContext);

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{sharedValue}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> MyComponent;
</code></pre>
<p>In the code above, the Context is created by assigning the imported <code>useContext</code> hook to the <code>MyComponent</code> function.</p>
<h3 id="heading-consumer">Consumer</h3>
<p>The Consumer component is used to consume the shared data within a component. It allows components to subscribe to the context changes and access the shared value. We might not see the consumer per say but it will use the information rendered by the provider. </p>
<p>It must always be nested inside the Provider because the Provider will render first to pass data to the components consuming the data. In otherwords, it must exist before you can consume it.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> MyContext <span class="hljs-keyword">from</span> <span class="hljs-string">'./MyComponent'</span>;

<span class="hljs-keyword">const</span> MyComponent = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> sharedValue = useContext(MyContext);

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{sharedValue}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> MyComponent;
</code></pre>
<p>In the code, the <code>MyComponent</code> component utilizes the <code>MyContext</code> context created earlier by using the <code>useContext</code>.</p>
<h2 id="heading-how-to-create-a-theme-switching-app-using-react-context">How to Create a Theme-Switching App using React Context.</h2>
<p>Let's implement a simple theme-switching application using React Context API.</p>
<h4 id="heading-step-1">Step #1</h4>
<p>In the <strong>src</strong> folder create a <strong>context</strong> folder. Then create a new file called <code>ThemeContext.js</code>. </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { createContext, useContext, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> ThemeContext = createContext();

<span class="hljs-keyword">const</span> ThemeProvider = <span class="hljs-function">(<span class="hljs-params">{ children }</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> [theme, setTheme] = useState(<span class="hljs-string">'light'</span>);

  <span class="hljs-keyword">const</span> toggleTheme = <span class="hljs-function">() =&gt;</span> {
    setTheme(<span class="hljs-function">(<span class="hljs-params">prevTheme</span>) =&gt;</span> (prevTheme === <span class="hljs-string">'light'</span> ? <span class="hljs-string">'dark'</span> : <span class="hljs-string">'light'</span>));
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ThemeContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">theme</span>, <span class="hljs-attr">toggleTheme</span> }}&gt;</span>
      {children}
    <span class="hljs-tag">&lt;/<span class="hljs-name">ThemeContext.Provider</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">const</span> useTheme = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> useContext(ThemeContext);
};

<span class="hljs-keyword">export</span> { ThemeProvider, useTheme };
</code></pre>
<h5 id="heading-walkthrough">Walkthrough:</h5>
<ul>
<li>We started by creating a context (<code>createContext()</code>) and assigning a <code>ThemeContext</code> variable to it, which will act as storage for the theme data.</li>
<li>In the <code>ThemeProvider</code> component, we used the <code>useState</code> hook to manage current theme and also create a toggle that will help with switching between light and dark mode.</li>
<li>The <code>&lt;ThemeContext.Provider&gt;</code> wraps the children, making the props passed to it available to every component within its subtree.</li>
<li>The <code>useTheme</code> component is a custom hook that uses <code>useContext()</code> to consume the <code>ThemeContext</code> context.</li>
</ul>
<h4 id="heading-step-2">Step #2</h4>
<p>In your <strong>src</strong> folder create a <code>ThemedComponent.js</code> file. Copy and paste the code below in the file:</p>
<pre><code class="lang-javscript">import React from 'react';
import { useTheme } from './context/ThemeContext';

const ThemedComponent = () =&gt; {
  const { theme, toggleTheme } = useTheme();

  return (
    &lt;div style={{ background: theme === 'light' ? '#fff' : '#333', color: theme === 'light' ? '#333' : '#fff' }}&gt;
      &lt;h2&gt;Themed Component&lt;/h2&gt;
      &lt;p&gt;Current Theme: {theme}&lt;/p&gt;
      &lt;button onClick={toggleTheme}&gt;Toggle Theme&lt;/button&gt;
    &lt;/div&gt;
  );
};

export default ThemedComponent;
</code></pre>
<h5 id="heading-walkthrough-1">Walkthrough:</h5>
<ul>
<li>Using the <code>useTheme()</code> hook, you can get access to consume the theme context. Remember that we passed  <code>theme</code> and the <code>toggleTheme</code> function to the <code>ThemeContext.Provider</code>.</li>
<li>The component's style dynamically changes based on the current theme. This shows how components can adapt to global state changes managed by the context.</li>
<li>The button triggers the <code>toggleTheme</code> function to switch between light and dark mode.</li>
</ul>
<h4 id="heading-step-3">Step #3</h4>
<p>In your <code>App.js</code> file, copy and paste the code below:</p>
<pre><code class="lang-javascript"><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> { ThemeProvider } <span class="hljs-keyword">from</span> <span class="hljs-string">'./context/ThemeContext'</span>;
<span class="hljs-keyword">import</span> ThemedComponent <span class="hljs-keyword">from</span> <span class="hljs-string">'./ThemedComponent.js'</span>;

<span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ThemeProvider</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">h1</span>&gt;</span>Themed App<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">ThemedComponent</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">ThemeProvider</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<h5 id="heading-walkthrough-2">Walkthrough:</h5>
<ul>
<li><code>&lt;App /&gt;</code> is the main app component where the <code>ThemeProvider</code> is used to wrap the whole application and give theme context access to all components within the <code>ThemeProvider</code>.</li>
<li>The <code>ThemedComponent</code> is rendered, showcasing the result of the components with access to the context.</li>
</ul>
<p>After successful implementation of context, the result should be like so:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/ezgif.com-video-to-gif-converter.gif" alt="Image" width="600" height="400" loading="lazy">
<em>A simple theme switch using react context.</em></p>
<p>This should help you implement the React Context API in your project.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you learned about context, context provider, context consumer, and how to create a React provider wrapper that manages the value of a context through component state. </p>
<p>You also learned about prop threading, prop drilling and its disadvantage relative to React context. </p>
<p>Finally, you learned how to retrieve values from a context using the <code>useContext</code> hook by building a simple theme switcher.</p>
<h2 id="heading-resources">Resources</h2>
<ul>
<li><a target="_blank" href="https://react.dev/reference/react/createContext">Official React Documentation on Context API</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=6RhOzQciVwI">React Context and Hooks - Video Tutorial</a></li>
</ul>
<p>Thanks for Reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Avoid Prop Drilling in React ]]>
                </title>
                <description>
                    <![CDATA[ By Ogundiran Ayobami In order to write scalable, reusable, and maintainable applications with React, you'll need to go beyond the surface of using React components, useEffect, useContext, useState, and the like. It involves learning in detail how Rea... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/avoid-prop-drilling-in-react/</link>
                <guid isPermaLink="false">66d84e6ac15439a8d5631e54</guid>
                
                    <category>
                        <![CDATA[ components ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React context ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 07 Nov 2023 22:58:39 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/11/Purple-Creative-Livestream-YouTube-Thumbnail.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Ogundiran Ayobami</p>
<p>In order to write scalable, reusable, and maintainable applications with React, you'll need to go beyond the surface of using React components, useEffect, useContext, useState, and the like. It involves learning in detail how React works in more depth. </p>
<p>And if you don't properly understand these key React concepts, you can run into various issues, like <a target="_blank" href="https://www.quora.com/What-is-prop-drilling-in-ReactJS">prop drilling</a>.</p>
<p>In this tutorial,  you'll learn what prop drilling is. I'll also teach you how to intuitively avoid it without relying on React context. In the end, you'll understand how to identify prop drilling without thinking and fix it with precision.</p>
<p>If you prefer a visual guide, here's a video version of this tutorial on my <a target="_blank" href="https://www.youtube.com/watch?v=ELZZnqHJhlw">YouTube channel here</a> (approximately 15 minutes).</p>
<p><a target="_blank" href="https://www.youtube.com/embed/ELZZnqHJhlw"><img src="https://img.youtube.com/vi/ELZZnqHJhlw/hqdefault.jpg" alt="Watch the video" width="480" height="360" loading="lazy"></a></p>
<h2 id="heading-what-is-prop-drilling">What is Prop Drilling?</h2>
<p>Prop drilling occurs when a parent component generates its state and passes it down as <code>props</code> to its children components that do not consume the props – instead, they only pass it down to another component that finally consumes it. </p>
<p>Below is an example of prop drilling in React:</p>
<pre><code class="lang-js"><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> [profile, setProfile] = useState({<span class="hljs-attr">ame</span>: <span class="hljs-string">'John'</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">Header</span> <span class="hljs-attr">profile</span>=<span class="hljs-string">{profile}</span> /&gt;</span> 
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span> 
  ); 
} 

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Header</span>(<span class="hljs-params">{ profile }</span>) </span>{ 
  <span class="hljs-keyword">return</span> ( 
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">header</span>&gt;</span> 
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>This is the header<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span> 
      <span class="hljs-tag">&lt;<span class="hljs-name">Content</span> <span class="hljs-attr">profile</span>=<span class="hljs-string">{profile}</span> /&gt;</span> 
    <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span></span> 
  ); 
} 

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Content</span>(<span class="hljs-params">{ profile }</span>) </span>{ 
  <span class="hljs-keyword">return</span> ( 
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">main</span>&gt;</span> 
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Content Component<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>{profile.name}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span> 
    <span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span></span> 
  ); 
} 

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>If you check out the example above, you'll notice that <code>profile</code> is passed from the <code>App</code> component through the <code>Header</code> to the <code>Content</code> component, which eventually makes use of the <code>props</code>. This is commonly referred to as prop drilling as the <code>Header</code> component doesn't consume the <code>prop</code> but only passes it down to the <code>Content</code> component that finally consumes it.</p>
<p>Now that you understand what prop drilling is, the next challenge is to figure out how to avoid it because it's not always an intuitive process. </p>
<p>You'll need to start exploring methods to address it. While you can use component composition and React context to resolve it, the challenge lies in not always recognizing the issue until later. </p>
<p>To truly master the art of handling prop drilling intuitively, you must learn how to identify elongated props and contexts.</p>
<h2 id="heading-what-is-an-elongated-prop">What is an Elongated Prop?</h2>
<p><img src="https://images.unsplash.com/photo-1484069560501-87d72b0c3669?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDV8fHF1ZXN0aW9uaW5nfGVufDB8fHx8MTY5OTMyMzQ0MXww&amp;ixlib=rb-4.0.3&amp;q=80&amp;w=2000" alt="Where is the love sung by The Black Eye Peas recreated in a tunnel underpass." width="2000" height="1333" loading="lazy">
_Photo by [Unsplash](https://unsplash.com/@emilymorter?utm_source=ghost&amp;utm_medium=referral&amp;utm_campaign=api-credit"&gt;Emily Morter / &lt;a href="https://unsplash.com/?utm_source=ghost&amp;utm_medium=referral&amp;utm<em>campaign=api-credit)</em></p>
<p>An elongated prop is a <code>prop</code> that is not consumed but it is only passed down to another component. When a component receives a <code>prop</code> from its parent and doesn't consume the <code>prop</code>, it passes the prop down to another component. This prop is called elongated prop because it has been extended.</p>
<p>Whenever you see a <code>prop</code> being passed down by components that neither creates nor consumes the <code>prop</code>, you have an an elongated prop (as well as prop drilling) in your code. The code snippet below is an example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Profile</span>(<span class="hljs-params">{ user }</span>) </span>{ 
  <span class="hljs-keyword">return</span> ( 
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">header</span>&gt;</span> 
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>This is the header<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span> 
      <span class="hljs-tag">&lt;<span class="hljs-name">Content</span> <span class="hljs-attr">user</span>=<span class="hljs-string">{user}</span> /&gt;</span> 
    <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span></span> 
  ); 
}
</code></pre>
<p><code>user</code>, in this example, is an elongated <code>prop</code> as it is neither created nor consumed by the <code>Profile</code> component. Instead, it is only passed down to the <code>Content</code> component. And that means we have extended <code>user</code> through a component that doesn't need it so that it can get to the one that does.</p>
<p>Now, let's revisit the example we used to illustrate prop drilling. Wait, are you thinking what I'm thinking? The <code>prop</code> that's being passed down in the prop drilling example is indeed an elongated prop, right? Yes, you've got it.</p>
<pre><code class="lang-js"><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> [profile, setProfile] = useState({<span class="hljs-attr">ame</span>: <span class="hljs-string">'John'</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">Header</span> <span class="hljs-attr">profile</span>=<span class="hljs-string">{profile}</span> /&gt;</span> 
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span> 
  ); 
} 

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Header</span>(<span class="hljs-params">{ profile }</span>) </span>{ 
  <span class="hljs-keyword">return</span> ( 
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">header</span>&gt;</span> 
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>This is the header<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span> 
      <span class="hljs-tag">&lt;<span class="hljs-name">Content</span> <span class="hljs-attr">profile</span>=<span class="hljs-string">{profile}</span> /&gt;</span> 
    <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span></span> 
  ); 
} 

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Content</span>(<span class="hljs-params">{ profile }</span>) </span>{ 
  <span class="hljs-keyword">return</span> ( 
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">main</span>&gt;</span> 
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Content Component<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>{profile.name}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span> 
    <span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span></span> 
  ); 
} 

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>In the code above, you can observe that the <code>prop</code> passed to <code>Header</code> is created in the <code>App</code> component. Then, <code>Header</code> passes it down to its child component named <code>Content</code>. As a result, the <code>profile</code> being passed down can be considered elongated because it is passed through a component (<code>Header</code>) that neither creates nor consumes it down to the one that does.</p>
<p>The <code>Header</code> component passing down the <code>prop</code> it doesn't create or need is unnecessarily stretching the context of the <code>prop</code>. </p>
<p>Now, the question is, how do elongated props help to intuitively avoid prop drilling in React? They make it easy for you to spot <code>props</code> being used where they're are neither created nor consumed.</p>
<p>Rather than focusing on how to solve prop drilling, elongated props enable you to avoid it. This is because it's intuitive to recognize when a component neither creates nor consumes <code>props</code>, and that helps you to know the component is irrelevant.</p>
<p>But before you learn how to quickly avoid prop drilling with your understanding of elongated props, it is important that you know the main causes of prop drilling. Then you'll truly know how to avoid it without thinking about it.</p>
<h2 id="heading-what-causes-prop-drilling">What Causes Prop Drilling?</h2>
<p><img src="https://images.unsplash.com/photo-1617575521317-d2974f3b56d2?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fHRyaWdnZXJ8ZW58MHx8fHwxNjk5MzIzNTU2fDA&amp;ixlib=rb-4.0.3&amp;q=80&amp;w=2000" alt="»What is your story?«" width="2000" height="1500" loading="lazy">
_Photo by [Unsplash](https://unsplash.com/@etiennegirardet?utm_source=ghost&amp;utm_medium=referral&amp;utm_campaign=api-credit"&gt;Etienne Girardet / &lt;a href="https://unsplash.com/?utm_source=ghost&amp;utm_medium=referral&amp;utm<em>campaign=api-credit)</em></p>
<p>Prop drilling doesn't occur out of thin air. It's a consequence of inadequate component organization, and it is not a React problem. It is a thinking or design problem. </p>
<p>You won't encounter an instance of prop drilling without observing one of the following layout mistakes:</p>
<p>First of all, <strong>grouping static elements and dependent components</strong> together to achieve an appealing UI design is the major cause of prop drilling. You can't avoid prop drilling when your UI groups static elements and dependent components together in a parent. The parent component clearly won't use the <code>prop</code>, as everything within it is a static element – except the component that needs a prop.</p>
<p>Here's an example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Header</span>(<span class="hljs-params">{ profile }</span>) </span>{ 
  <span class="hljs-keyword">return</span> ( 
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">header</span>&gt;</span> 
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>This is the header<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span> 
      <span class="hljs-tag">&lt;<span class="hljs-name">Content</span> <span class="hljs-attr">profile</span>=<span class="hljs-string">{profile}</span> /&gt;</span> 
    <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span></span> 
  ); 
}
</code></pre>
<p>In this case, static elements <code>&lt;header&gt; and &lt;h1&gt;</code> are grouped with a dependent component <code>Content</code> – and that's why we have prop drilling therein. </p>
<p>Provided that the <code>Content</code> component is independent or takes no <code>props</code>, it won't need <code>profile</code> and there won't be prop drilling in the first place. This is why forcing a component that should be independent to take <code>props</code> from its parent is a recipe for prop drilling in React.</p>
<p>Second of all, when a <strong>component accepts <code>props</code> that it doesn't use but merely passes it down to its children</strong>, this is a sign that you have prop drilling in your component: </p>
<pre><code class="lang-js"><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> [profile, setProfile] = useState({<span class="hljs-attr">name</span>: <span class="hljs-string">"Ayobami"</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">Parent</span> <span class="hljs-attr">profile</span>=<span class="hljs-string">{profile}</span> /&gt;</span> 
    <span class="hljs-tag">&lt;/&gt;</span></span>
 ); 
}; 

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Parent</span>(<span class="hljs-params">{ profile }</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">Hero</span> <span class="hljs-attr">profile</span>=<span class="hljs-string">{profile}</span> /&gt;</span> 
      <span class="hljs-tag">&lt;<span class="hljs-name">Features</span> <span class="hljs-attr">profile</span>=<span class="hljs-string">{profile}</span> /&gt;</span> 
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
 ); 
};
</code></pre>
<p>In this case there is prop drilling because the <code>Parent</code> component takes <code>profile</code> and it doesn't use it though it passes it down to its children. </p>
<p>Third, when a component that represents an independent section of a page is <strong>forced to take props from its parent</strong>, prop drilling is inevitable. It should ideally be self-contained with its state and operations. </p>
<p>The exception would be if it's intentionally tied to its parent for specific reasons. In such cases, prop drilling becomes a necessary trade-off.  </p>
<p>If you revisit the example of prop drilling cited in this article, you will realize it has a prop drilling issue because the <code>Content</code> component which could have been an independent component by having a state is forced to receive props from its parent.</p>
<p>And finally, <strong>the presence of elongated <code>props</code></strong> is a sure sign of prop drilling. Since an elongated prop is a fundamental element that's consistently present in every case of prop drilling, grasping this concept allows you to instinctively avoid prop drilling. </p>
<p>When you spot an elongated prop, you can be certain that one of the other three mistakes is also in play. In short, an elongated prop is a prop that is not consumed and is also passed down to another component.</p>
<p>So grouping static elements with dependent components, forcing components to take props, elongated props, and receiving a prop without consuming it are the signs to recognize prop drilling in React.</p>
<h2 id="heading-how-to-fix-prop-drilling-with-component-composition">How to Fix Prop Drilling with Component Composition</h2>
<p>Component composition is a good approach to fix prop drilling. If you ever find yourself in a situation where a component passes down a prop it neither creates nor consumes, you can use component composition to fix it. </p>
<p>But to use component composition, you need to understand a component context.</p>
<h3 id="heading-what-is-a-component-context">What is a component context?                           ‌</h3>
<p>The context of a component encompasses everything that is visible within it, including state, props, and children. The following code further illustrates this concept:</p>
<pre><code class="lang-js"><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> [profile, setProfile] = useState({<span class="hljs-attr">name</span>: <span class="hljs-string">'Ayobami'</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">Header</span> <span class="hljs-attr">profile</span>=<span class="hljs-string">{profile}</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> App;
</code></pre>
<p>In this scenario, the context of <code>App</code> refers to everything we can see within the <code>App</code> component – including the <code>profile</code> prop, the <code>Header</code>, and other <code>App</code> content. Therefore, any data created in the <code>App</code> component should ideally be utilized within the <code>App</code> component itself, either as its own data or as <code>props</code> to its children.</p>
<p>Prop drilling always emerges when the children receiving the <code>props</code> doesn't consume it but only passes it down to its children.  </p>
<p>To avoid prop drilling in this case, any grandchildren components that require access to the same <code>props</code>, especially when their parent don't consume the data, should be passed as children ensuring that the data remains within the <code>App</code> context.</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</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> [profile, setProfile] = useState({<span class="hljs-attr">name</span>: <span class="hljs-string">'Ayobami'</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">Header</span>&gt;</span> 
        <span class="hljs-tag">&lt;<span class="hljs-name">Content</span> <span class="hljs-attr">profile</span>=<span class="hljs-string">{profile}</span> /&gt;</span> 
      <span class="hljs-tag">&lt;/<span class="hljs-name">Header</span>&gt;</span> 
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span> 
  ); 
}
</code></pre>
<p><strong><code>Or</code></strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">export</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> [profile, setProfile] = useState({<span class="hljs-attr">name</span>: <span class="hljs-string">'Ayobami'</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">Header</span> <span class="hljs-attr">children</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">Content</span> <span class="hljs-attr">profile</span>=<span class="hljs-string">{profile}</span> /&gt;</span>} &gt; 
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span> 
  ); 
}</span>
</code></pre>
<p>As you can see, we have resolved the prop drilling issue in the previous example, even though we still have a redundant component, <code>&lt;Header&gt;</code>, right? We've successfully addressed prop drilling through component composition. </p>
<p>This process is quite straightforward because we concentrate on recognizing elongated props and repositioning them within appropriate contexts.</p>
<p>The concept of prop drilling is problem-focused, but prop elongation is solution-driven. When dealing with elongated props, our primary goal is to identify props that are not consumed but only passed down to another components.</p>
<h2 id="heading-how-to-fix-prop-drilling-by-moving-state-to-the-consumer">How to Fix Prop Drilling by Moving State to the Consumer</h2>
<p>Prop drilling can also be fixed by moving state to where it is consumed. The example of prop drilling in this article has a component named <code>Content</code>. But the component is forced to receive a <code>prop</code> from its parent instead of having a state and be an independent component – and so we have prop drilling. </p>
<p>We can fix the prop drilling in this case by moving the profile state to where it is consumed.</p>
<p>Let's revisit the example:</p>
<pre><code class="lang-js"><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> [profile, setProfile] = useState({<span class="hljs-attr">ame</span>: <span class="hljs-string">'John'</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">Header</span> <span class="hljs-attr">profile</span>=<span class="hljs-string">{profile}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Footer</span> <span class="hljs-attr">profile</span>=<span class="hljs-string">{profile</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span> 
  ); 
} 

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Header</span>(<span class="hljs-params">{ profile }</span>) </span>{ 
  <span class="hljs-keyword">return</span> ( 
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">header</span>&gt;</span> 
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>This is the header<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span> 
      <span class="hljs-tag">&lt;<span class="hljs-name">Content</span> <span class="hljs-attr">profile</span>=<span class="hljs-string">{profile}</span> /&gt;</span> 
    <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span></span> 
  ); 
} 

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Content</span>(<span class="hljs-params">{ profile }</span>) </span>{ 
  <span class="hljs-keyword">return</span> ( 
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">main</span>&gt;</span> 
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Content Component<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>{profile.name}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span> 
    <span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span></span> 
  ); 
} 

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>We can fix prop drilling in this case by moving <code>profile</code> to where it is consumed:</p>
<pre><code class="lang-js"><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">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">Header</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Footer</span> <span class="hljs-attr">profile</span>=<span class="hljs-string">{profile</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span> 
  ); 
} 

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Header</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">header</span>&gt;</span> 
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>This is the header<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span> 
      <span class="hljs-tag">&lt;<span class="hljs-name">Content</span> /&gt;</span> 
    <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span></span> 
  ); 
} 

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Content</span>(<span class="hljs-params">{ profile }</span>) </span>{ 
  <span class="hljs-keyword">const</span> [profile, setProfile] = useState({<span class="hljs-attr">ame</span>: <span class="hljs-string">'John'</span>});
  <span class="hljs-keyword">return</span> ( 
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">main</span>&gt;</span> 
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Content Component<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>{profile.name}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span> 
    <span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span></span> 
  ); 
}
</code></pre>
<p>Now that we have lifted the profile to the <code>Content</code> component where it is consumed, the <code>App</code> component doesn't have a state, while the <code>Header</code> component doesn't receive a prop again as the <code>Content</code> component has its state.</p>
<p>But wait! There is a problem. The <code>Footer</code> component needs the state we moved away from <code>App</code>. There you are! That is the problem with lifting or moving state to where we think it is needed. In this case, if the <code>Footer</code> component doesn't need it, we won't have any issue – but <code>Footer</code> also needs the prop. </p>
<p>Now that <code>Footer</code> needs <code>profile</code> as a prop, we need to solve prop drilling with another method.</p>
<h2 id="heading-how-to-fix-prop-drilling-with-a-children-replacing-parent-strategy">How to Fix Prop Drilling with a Children-Replacing-Parent Strategy</h2>
<p>Earlier in this article, we talked about how to use component composition and moving state to its consumer to solve prop drilling. But as you saw, they have some issues – duplicated components or states.</p>
<p>But using this children-replacing-parent approach fixes the problem effectively:</p>
<p><strong>Working but could be better:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">export</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> [profile, setProfile] = useState({<span class="hljs-attr">name</span>: <span class="hljs-string">'Ayobami'</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">Header</span>&gt;</span> 
        <span class="hljs-tag">&lt;<span class="hljs-name">Content</span> <span class="hljs-attr">profile</span>=<span class="hljs-string">{profile}</span> /&gt;</span> 
      <span class="hljs-tag">&lt;/<span class="hljs-name">Header</span>&gt;</span> 
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span> 
  ); 
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Header</span>(<span class="hljs-params">{ profile }</span>) </span>{ 
  <span class="hljs-keyword">return</span> ( 
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">header</span>&gt;</span> 
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>This is the header<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span> 
      <span class="hljs-tag">&lt;<span class="hljs-name">Content</span> <span class="hljs-attr">profile</span>=<span class="hljs-string">{profile}</span> /&gt;</span> 
    <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span></span> 
  ); 
}
</code></pre>
<p>The example above shows a solution to the prop drilling example in this article. But as you can see, it has a redundant component, as <code>Header</code> does nothing.</p>
<p><strong>Here's a </strong>better version:<em>**</em></p>
<pre><code class="lang-js"><span class="hljs-keyword">export</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> [profile, setProfile] = useState({<span class="hljs-attr">name</span>: <span class="hljs-string">'Ayobami'</span>}); 
  <span class="hljs-keyword">return</span> ( 
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">header</span>&gt;</span> 
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>This is the header<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span> 
      <span class="hljs-tag">&lt;<span class="hljs-name">Content</span> <span class="hljs-attr">profile</span>=<span class="hljs-string">{profile}</span> /&gt;</span> 
    <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span></span> 
  ); 
}
</code></pre>
<p>In the above code, we enhance the component composition solution we previously implemented for the prop drilling example by replacing the redundant <code>Header</code> component with its content in its parent (<code>App</code>).</p>
<h2 id="heading-what-to-avoid">What to Avoid</h2>
<p><img src="https://images.unsplash.com/photo-1587065915399-8f8c714ab540?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDEwfHxkYW5nZXJ8ZW58MHx8fHwxNjk5MzIzMDgxfDA&amp;ixlib=rb-4.0.3&amp;q=80&amp;w=2000" alt="Image" width="2000" height="1333" loading="lazy">
_Photo by [Unsplash](https://unsplash.com/@edwinhooper?utm_source=ghost&amp;utm_medium=referral&amp;utm_campaign=api-credit"&gt;Edwin Hooper / &lt;a href="https://unsplash.com/?utm_source=ghost&amp;utm_medium=referral&amp;utm<em>campaign=api-credit)</em></p>
<p>It's essential to highlight what to avoid when dealing with prop drilling to prevent unnecessary challenges.</p>
<ul>
<li><strong>Avoid React Context, if possible, to fix prop drilling.</strong> This approach ties your component to a specific context, restricting its usability outside of that context and hindering composition and reusability.</li>
<li><strong>Steer clear of redundant components by employing a children-parent replacement approach.</strong> This approach naturally incorporates <a target="_blank" href="https://www.codementor.io/@dinerismail/the-power-of-component-composition-in-react-21goassg4m">component composition</a> without introducing redundant components or states when resolving prop drilling.</li>
</ul>
<p>By avoiding elongated props, you pave the way for crafting maintainable, high-performing, reusable, and scalable React components. It simplifies the process of lifting states and components by removing the struggle of deciding where to place them. </p>
<p>With your understanding of elongated props, you can confidently position props and components within the right context without undue stress.</p>
<p>In short, you can now discover prop drilling intuitively by paying attention to any component that takes <code>props</code> it doesn't consume and only passes it down to another component. </p>
<p>Thanks for reading – cheers!</p>
<p>Hey wait! I am <a target="_blank" href="https://twitter.com/codingnninja">Ayobami Ogundiran</a> and I am about to start showing how to build your own React, Redux, TypeScript, Zod or Ecommerce websites on my YouTube channel. <a target="_blank" href="https://youtube.com/youtoocancode">Click to subscribe</a> to stay connected. </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use the React Context API in Your Projects ]]>
                </title>
                <description>
                    <![CDATA[ Managing state is an essential part of developing applications in React. A common way to manage state is by passing props. Passing props means sending data from one component to another. It's a good way to make sure that data gets to the right place ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/context-api-in-react/</link>
                <guid isPermaLink="false">66bd904bdc6141cf21aaada1</guid>
                
                    <category>
                        <![CDATA[ api ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React context ]]>
                    </category>
                
                    <category>
                        <![CDATA[ State Management  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Boateng Dickson ]]>
                </dc:creator>
                <pubDate>Wed, 29 Mar 2023 20:04:36 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/context-api-cover-main.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Managing state is an essential part of developing applications in React. A common way to manage state is by passing props. Passing props means sending data from one component to another. It's a good way to make sure that data gets to the right place in a React application. </p>
<p>But it can be annoying to pass props when you have to send the same data to lots of components or when components are far away from each other. This can make an application slower and harder to work with.</p>
<p>Fortunately, React provides a built-in feature known as the context API that helps  “teleport” data to the components that need it without passing props. </p>
<p>In this article, we'll explore how the context API works and how to use it effectively in your React applications.</p>
<h2 id="heading-the-problem-with-passing-props">The Problem with Passing Props</h2>
<p>In React, passing props is a fundamental concept that enables a parent component to share data with its child components as well as other components within an application. </p>
<p>In many cases, passing props can be an effective way to share data between different parts of your application. But passing props down a chain of multiple components to reach a specific component can make your code overly cumbersome. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-198.png" alt="Image" width="600" height="400" loading="lazy">
<em>Illustration of passing props from parent to children</em></p>
<p>From the above diagram, to pass data down to the component "Child B", we need to pass it down through all the intermediate components, even if those components don't actually use the data themselves. This is what is referred to as "prop drilling." </p>
<p>Prop drilling can make your code more difficult to read and maintain, and can also make it harder to refactor your components later on.</p>
<p>This is where the Context API comes in. With Context API, you can store data at the top level of the component tree and make it available to all other components that need it without passing props.</p>
<h2 id="heading-how-the-context-api-works">How the Context API Works</h2>
<p>Context API allows data to be passed through a component tree without having to pass props manually at every level. This makes it easier to share data between components.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-197.png" alt="Image" width="600" height="400" loading="lazy">
<em>A diagram illustrating how Context API works</em></p>
<p>For example, let’s say you have a shopping app with a component that shows a user’s shopping cart, and another component that shows the user’s order history.</p>
<p>With Context API, you can create a “context” that holds the user’s shopping information, like their cart and order history. Then, you can use that context in both the shopping cart and the order history component, without having to pass the information down through props.</p>
<p>It’s like having a big box that holds all the things you need for your shopping trip. You can take things out of the box when you need them, and put them back in when you’re done. </p>
<p>Basically, Context API consists of two main components: the context provider and the context consumer. The provider is responsible for creating and managing the context, which holds the data to be shared between components. On the other hand, the consumer is used to access the context and its data from within a component. </p>
<p>In the example given, the provider will create the context that holds the user's shopping information, while the consumer components (shopping cart and order history) will access that context to retrieve the data they need. This avoids the need to pass the information down through props, making your code more efficient and easier to manage.</p>
<h2 id="heading-how-to-get-started-with-the-context-api">How to Get Started with the Context API</h2>
<p>To start using the Context API in your applications, you'll need to follow a few simple steps:</p>
<h3 id="heading-1-create-a-context-object">1. Create a Context Object</h3>
<p>First, you need to create a context object using the <code>createContext</code> function from the 'react' library. This context object will hold the data that you want to share across your application. </p>
<p>Create a new file named <code>MyContext.js</code> in the <code>src</code> folder and add the following code to create a context object:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { createContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> MyContext = createContext(<span class="hljs-string">""</span>);
</code></pre>
<p>In the above code, we're importing <code>createContext</code> from React and using it to create a new context object named "MyContext". Then, we are exporting the context object so that we can use it in other parts of our application.</p>
<h3 id="heading-2-wrap-components-with-a-provider">2. Wrap Components with a Provider</h3>
<p>Once you've created a context object, you need to wrap the components that need access to the shared data with a Provider component. The Provider component accepts a "value" prop that holds the shared data, and any component that is a child of the Provider component can access that shared data.</p>
<p>It's important to note that the Provider component should be wrapped around the top-level component in an application to ensure that all child components have access to the shared data.</p>
<p>Here's an example that demonstrates how to wrap components with a Provider in Context API:</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// Create a parent component that wraps child components with a Provider</span>

<span class="hljs-keyword">import</span> { useState, React } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { MyContext } <span class="hljs-keyword">from</span> <span class="hljs-string">"./MyContext"</span>;
<span class="hljs-keyword">import</span> MyComponent <span class="hljs-keyword">from</span> <span class="hljs-string">"./MyComponent"</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> [text, setText] = useState(<span class="hljs-string">""</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">MyContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">text</span>, <span class="hljs-attr">setText</span> }}&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">MyComponent</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">MyContext.Provider</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> App;
</code></pre>
<p>In this example, we have a parent component called App. This component has a state variable called "text", which is initially set to an empty string. We've also defined a function called <code>setText</code> that can be used to update the value of <code>text</code>.</p>
<p>Inside the return statement of the App component, we've wrapped the children of this component with the provider component ("MyContext.Provider"). Then we've passed an object to the value prop of the provider component that contains "text" and "setText" values.</p>
<h3 id="heading-3-consume-the-context">3. Consume the Context</h3>
<p>Now that we've created the provider component, we need to consume the context in other components. To do this, we use the "useContext" hook from React. </p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { MyContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'./MyContext'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> { text, setText } = useContext(MyContext);

  <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>{text}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</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> setText('Hello, world!')}&gt;
        Click me
      <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>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> MyComponent;
</code></pre>
<p>In this example, we've used the useContext hook to access the "text" and "setText" variables that were defined in the provider component.</p>
<p>Inside the return statement of "MyComponent", we've rendered a paragraph element that displays the value of <code>text</code>. We've also rendered a button that, when clicked, will call the <code>setText</code> function to update the value of <code>text</code> to "Hello, world!".</p>
<p><img src="https://i.imgur.com/a191j3C.gif" width="716" height="472" alt="a191j3C" loading="lazy"></p>
<p>And that's it! This is how you can use the Context API in your React application. </p>
<p>By creating a context object, defining a provider component, and consuming the context in other components, you can share data across your application in a simple and efficient way.</p>
<h2 id="heading-use-cases-of-context-api">Use Cases of Context API</h2>
<p>Here are some real-world use cases of Context API.</p>
<ol>
<li><strong>Theming:</strong> You can use Context API to store the current theme of your application and make it available to all components. This way, whenever the user switches the theme (such as enabling dark mode), all components will be updated with the new theme.</li>
<li><strong>User Authentication:</strong> You can also use Context API to store a user's authentication status and pass it down to all the components that need it. This way, you can easily restrict access to certain parts of your application based on the user's authentication status.</li>
<li><strong>Multilingual Support:</strong> You can store the current language of your application in the context and pass it down to all the components that need it. This way, you can easily switch between different languages without having to pass the language down as props to all the components.</li>
<li><strong>Accessing data from external sources:</strong> Finally, you can use the Context API to store data retrieved from external sources such as APIs or databases and make it available to all components. This can simplify your code and make it easier to manage data across your application.</li>
</ol>
<p>Overall, Context API provides a flexible and efficient way to manage state data across your application, and it can be particularly useful for managing global data that needs to be shared between multiple components.</p>
<h2 id="heading-best-practices-for-context-api">Best Practices for Context API</h2>
<p>As with any tool, there are best practices and common pitfalls to keep in mind when using the Context API in your projects. Here are some tips for effective use of the Context API:</p>
<ol>
<li>Use a separate file to define your Context: It's a good practice to define your context object in a separate file to keep your code organized and easy to maintain. </li>
<li>Keep Context API limited to global state management only: It's best to use the Context API for managing state that needs to be accessed across multiple components in your application. Avoid using it for state that only needs to be accessed within a single component, as it can lead to unnecessary complexity and performance issues.</li>
<li>Use context providers sparingly: While context providers can be a powerful tool for managing global state, it's generally a good idea to use them sparingly. Instead, consider using props to pass data down through your component tree whenever possible.</li>
<li>Use default values: When creating a new context, it's a good idea to provide a default value that will be used if no provider is present. This can help prevent unexpected errors and make your code more robust. Note that, for the project we did above, we used an empty string as the default value for the context object. </li>
</ol>
<h2 id="heading-recap">Recap</h2>
<p>In this article, we explored the React Context API, a powerful tool for managing state in React applications.</p>
<p>We have walked through the basics of the Context API, including creating a context, creating a Provider component to pass data to child components, and consuming data in other component using the <code>useContext</code> hook.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>If you're interested in exploring how to implement a light/dark mode theme in your own React projects using the Context API, I've created a simple website that demonstrates how to do just that. You can find the code for the project on my <a target="_blank" href="https://github.com/dboatengg/context-api-tutorial">GitHub</a>. </p>
<p>By exploring the code and experimenting with your own modifications, you'll be well on your way to mastering the Context API and unlocking its full potential in your own projects. </p>
<p>Thank you for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Avoid Prop Drilling with the React Context API ]]>
                </title>
                <description>
                    <![CDATA[ The React Context API provides a way to pass data through multiple nested levels of components without having to manually pass that data to each level.  React context is one sure way of globally managing your data in your app, and it's a good way to ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/avoid-prop-drilling-with-react-context-api/</link>
                <guid isPermaLink="false">66c8c8550f021017a28a49c6</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React context ]]>
                    </category>
                
                    <category>
                        <![CDATA[ State Management  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Israel Chidera ]]>
                </dc:creator>
                <pubDate>Thu, 13 Oct 2022 16:52:03 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/10/ferenc-almasi-c8h0n7fSTqs-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The React Context API provides a way to pass data through multiple nested levels of components without having to manually pass that data to each level. </p>
<p>React context is one sure way of globally managing your data in your app, and it's a good way to avoid prop drilling. </p>
<p>In this tutorial, we will learn how to use the React context API (useContext hook) to avoid prop drilling.</p>
<h2 id="heading-what-is-prop-drilling">What is Prop Drilling?</h2>
<p>In a traditional React application, data is often shared between components using props. Manually sharing this data can be hectic, especially when shared between multiple nested components. Also, sharing data between two child components can be cumbersome. Hence the need for global state management. </p>
<p><strong>Prop drilling</strong> is a situation where data is passed from one component through multiple interdependent components until you get to the component where the data is needed. Here's an illustration of prop drilling to help you understand:  </p>
<p><img src="https://lh5.googleusercontent.com/K1veBT9r_aQPq_iYI9MdtljbsBu8egv7n8cu78fWqzL0POVn2xb66r_gEFgJ8qg9FxphsGFqNZIDQ3QZ0zuT-XtEcrpNVZylXvxhDTPAySL8_FJWiIGHlcXggcHYCFKaQeNp8HRQvCZZQHRULaf8_vtg8mgyZElVhkSiUYgicFQ0mo6zPgGve9-Pcg" alt="Image" width="1280" height="800" loading="lazy"></p>
<p>Passing data through multiple components is not a good way of writing clean, reusable, and DRY code. </p>
<p>The React context API is a fast way of avoiding prop drilling and ensuring your data is managed globally without using a huge third-party state management app like <a target="_blank" href="https://redux.js.org/">Redux</a> and <a target="_blank" href="https://mobx.js.org/README.html">MobX</a>.</p>
<h2 id="heading-what-is-the-react-context-api">What is the React Context API?</h2>
<p>React context is a built-in API that uses the useContext hook to share data across components. </p>
<p>Imagine passing the data of an authenticated user from a parent component to a deep nested child component. This will be cumbersome if you need to pass the data through a lot of intermediate components. </p>
<p>A better approach to doing this is using React context to handle the data.  </p>
<h2 id="heading-how-to-use-the-react-context-api">How to Use the React Context API</h2>
<h3 id="heading-how-to-create-context">How to create context</h3>
<p>useContext is a built-in hook in React. You can start using the context API by importing the createContext function from React like this:</p>
<pre><code class="lang-app.js">Import {createContext} from ‘react’;
const AuthContext = createContext();
</code></pre>
<p>Here, we initialized our context and named it <strong>AuthContext.</strong> The next step is to provide the context.</p>
<h3 id="heading-how-to-provide-the-context-to-the-components-that-need-it">How to provide the context to the components that need it</h3>
<p>The context API uses a provider to pass data to its child components. You will have to wrap all components with a provider component.</p>
<pre><code class="lang-app.js">&lt;AuthContext.Provider value={...}&gt;
    &lt;ParentComponent/&gt;
&lt;AuthContext.Provider&gt;
</code></pre>
<p>The Provider component has a <strong>value</strong> prop as seen above. The value of the context can either be updated or set using the <strong>value</strong> prop. In our case, we will be setting the value prop to the name of our authenticated user.</p>
<pre><code class="lang-app.js">import React from ‘react’;

function App() {

    const username = “John Doe”

    return(
        &lt;AuthContext.Provider value={username}&gt;
            &lt;Dashboard/&gt;
        &lt;AuthContext.Provider&gt;
    )
}

export default App;
</code></pre>
<p>Hooray! All components inside this <strong>App</strong> component will have access to the username data. Next, let's see how to use the context.</p>
<h3 id="heading-how-to-consume-the-context">How to consume the context</h3>
<p>We can consume the context by using the <strong>useContext</strong> hook. Without passing data through nested components, you can access your context in any component you want. Here’s how.</p>
<pre><code class="lang-profile.js">import { useContext } from ‘react’;

const Profile = () =&gt; {

    const value = useContext(AuthContext);

    return (
        &lt;div&gt;
            {value}
        &lt;/div&gt;
    )
}

export default Profile
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Apart from solving the problem of prop drilling, you can also use React context for theme configuration, global state management and more. </p>
<p>Note that the React context API is not a replacement for a global state management tool like Redux and MobX. You can read more about React Context <a target="_blank" href="https://reactjs.org/docs/context.html">here</a>.</p>
<p>I hope you enjoyed this tutorial.</p>
<p><strong>Happy coding!</strong></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ React Context for Beginners – The Complete Guide (2021) ]]>
                </title>
                <description>
                    <![CDATA[ React context is an essential tool for every React developer to know. It lets you easily share state in your applications. In this comprehensive guide, we will cover what React context is, how to use it, when and when not to use context, and lots mor... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-context-for-beginners/</link>
                <guid isPermaLink="false">66d037bbab216b4115759484</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React context ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Reed ]]>
                </dc:creator>
                <pubDate>Wed, 21 Jul 2021 15:39:28 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/07/react-context-for-beginners.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>React context is an essential tool for every React developer to know. It lets you easily share state in your applications.</p>
<p>In this comprehensive guide, we will cover what React context is, how to use it, when and when not to use context, and lots more.</p>
<p>Even if you've never worked with React context before, you're in the right place. You will learn everything you need to know with simple, step-by-step examples.</p>
<p>Let's get started!</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-what-is-react-context">What is React context?</a></li>
<li><a class="post-section-overview" href="#heading-when-should-you-use-react-context">When should you use React context?</a></li>
<li><a class="post-section-overview" href="#heading-what-problems-does-react-context-solve">What problems does React context solve?</a></li>
<li><a class="post-section-overview" href="#heading-how-do-i-use-react-context">How do I use React context?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-the-usecontext-hook">What is the useContext hook?</a></li>
<li><a class="post-section-overview" href="#heading-you-may-not-need-context">You may not need context</a></li>
<li><a class="post-section-overview" href="#heading-does-react-context-replace-redux">Does React context replace Redux?</a></li>
<li><a class="post-section-overview" href="#heading-react-context-caveats">React context caveats</a></li>
</ul>
<h2 id="heading-what-is-react-context">What is React context?</h2>
<p>React context allows us to pass down and use (consume) data in whatever component we need in our React app without using props.</p>
<p><em>In other words, React context allows us to share data (state) across our components more easily.</em></p>
<h2 id="heading-when-should-you-use-react-context">When should you use React context?</h2>
<p>React context is great when you are passing data that can be used in any component in your application.</p>
<p><strong>These types of data include:</strong></p>
<ul>
<li>Theme data (like dark or light mode)</li>
<li>User data (the currently authenticated user)</li>
<li>Location-specific data (like user language or locale)</li>
</ul>
<p>Data should be placed on React context that does not need to be updated often. </p>
<p>Why? Because context was not made as an entire state management system. It was made to make consuming data easier.</p>
<p><em>You can think of React context as the equivalent of global variables for our React components.</em></p>
<h2 id="heading-what-problems-does-react-context-solve">What problems does React context solve?</h2>
<p>React context helps us avoid the problem of props drilling.</p>
<p><strong>Props drilling</strong> is a term to describe when you pass props down multiple levels to a nested component, through components that don't need it.</p>
<p>Here is an example of props drilling. In this application, we have access to theme data that we want to pass as a prop to all of our app's components. </p>
<p>As you can see, however, the direct children of <code>App</code>, such as <code>Header</code>, also have to pass the theme data down using props.</p>
<pre><code class="lang-js"><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">{ theme }</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">Header</span> <span class="hljs-attr">theme</span>=<span class="hljs-string">{theme}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Main</span> <span class="hljs-attr">theme</span>=<span class="hljs-string">{theme}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Sidebar</span> <span class="hljs-attr">theme</span>=<span class="hljs-string">{theme}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Footer</span> <span class="hljs-attr">theme</span>=<span class="hljs-string">{theme}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Header</span>(<span class="hljs-params">{ theme }</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">User</span> <span class="hljs-attr">theme</span>=<span class="hljs-string">{theme}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Login</span> <span class="hljs-attr">theme</span>=<span class="hljs-string">{theme}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Menu</span> <span class="hljs-attr">theme</span>=<span class="hljs-string">{theme}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
}
</code></pre>
<p><em>What is the issue with this example?</em></p>
<p>The issue is that we are drilling the <code>theme</code> prop through multiple components that don't immediately need it.</p>
<p>The <code>Header</code> component doesn't need <code>theme</code> other than to pass it down to its child component. In other words, it would be better for <code>User</code> , <code>Login</code> and <code>Menu</code> to consume the <code>theme</code> data directly.</p>
<p>This is the benefit of React context – we can bypass using props entirely and therefore avoid the issue of props drilling.</p>
<h2 id="heading-how-do-i-use-react-context">How do I use React context?</h2>
<p>Context is an API that is built into React, starting from React version 16.</p>
<p>This means that we can create and use context directly by importing React in any React project.</p>
<p><strong>There are four steps to using React context:</strong></p>
<ol>
<li>Create context using the <code>createContext</code> method.</li>
<li>Take your created context and wrap the context provider around your component tree.</li>
<li>Put any value you like on your context provider using the <code>value</code> prop.</li>
<li>Read that value within any component by using the context consumer.</li>
</ol>
<p><em>Does all this sound confusing?</em> It's simpler than you think.</p>
<p>Let's take a look at a very basic example. In our <code>App</code>, let's pass down our own name using Context and read it in a nested component: <code>User</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> UserContext = React.createContext();

<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">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">UserContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Reed"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">User</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">UserContext.Provider</span>&gt;</span></span>
  )
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">User</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">UserContext.Consumer</span>&gt;</span>
      {value =&gt; <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{value}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>} 
      {/* prints: Reed */}
    <span class="hljs-tag">&lt;/<span class="hljs-name">UserContext.Consumer</span>&gt;</span></span>
  )
}
</code></pre>
<p>Let's break down what we are doing, step-by-step:</p>
<ol>
<li>Above our <code>App</code> component, we are creating context with <code>React.createContext()</code> and putting the result in a variable, <code>UserContext</code>. In almost every case, you will want to export it as we are doing here because your component will be in another file. Note that we can pass an initial value to our <code>value</code> prop when we call <code>React.createContext()</code>.</li>
<li>In our <code>App</code> component, we are using <code>UserContext</code>. Specifically <code>UserContext.Provider</code>. The created context is an object with two properties: <code>Provider</code> and <code>Consumer</code>, both of which are components. To pass our value down to every component in our App, we wrap our Provider component around it (in this case, <code>User</code>).</li>
<li>On <code>UserContext.Provider</code>, we put the value that we want to pass down our entire component tree. We set that equal to the <code>value</code> prop to do so. In this case, it is our name (here, Reed).</li>
<li>In <code>User</code>, or wherever we want to consume (or use) what was provided on our context, we use the consumer component: <code>UserContext.Consumer</code>. To use our passed down value, we use what is called the <strong>render props pattern</strong>. It is just a function that the consumer component gives us as a prop. And in the return of that function, we can return and use <code>value</code>.</li>
</ol>
<h2 id="heading-what-is-the-usecontext-hook">What is the useContext hook?</h2>
<p>Looking at the example above, the render props pattern for consuming context may look a bit strange to you.</p>
<p>Another way of consuming context became available in React 16.8 with the arrival of React hooks. We can now consume context with the <strong>useContext hook</strong>.</p>
<p>Instead of using render props, we can pass the entire context object to <code>React.useContext()</code> to consume context at the top of our component. </p>
<p>Here is the example above using the useContext hook:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> UserContext = React.createContext();

<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">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">UserContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Reed"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">User</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">UserContext.Provider</span>&gt;</span></span>
  )
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">User</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> value = React.useContext(UserContext);  

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{value}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
}
</code></pre>
<p><em>The benefit of the useContext hook is that it makes our components more concise and allows us to create our own custom hooks.</em></p>
<p>You can either use the consumer component directly or the useContext hook, depending on which pattern you prefer.</p>
<h2 id="heading-you-may-not-need-context">You may not need context</h2>
<p>The mistake many developers make is reaching for context when once they have to pass props down several levels to a component.</p>
<p>Here is an application with a nested <code>Avatar</code> component that requires two props <code>username</code> and <code>avatarSrc</code> from the <code>App</code> component.</p>
<pre><code class="lang-js"><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">{ user }</span>) </span>{
  <span class="hljs-keyword">const</span> { username, avatarSrc } = user;

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">main</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Navbar</span> <span class="hljs-attr">username</span>=<span class="hljs-string">{username}</span> <span class="hljs-attr">avatarSrc</span>=<span class="hljs-string">{avatarSrc}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span></span>
  );
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Navbar</span>(<span class="hljs-params">{ username, avatarSrc }</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">nav</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Avatar</span> <span class="hljs-attr">username</span>=<span class="hljs-string">{username}</span> <span class="hljs-attr">avatarSrc</span>=<span class="hljs-string">{avatarSrc}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">nav</span>&gt;</span></span>
  );
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Avatar</span>(<span class="hljs-params">{ username, avatarSrc }</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">{avatarSrc}</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">{username}</span> /&gt;</span></span>;
}
</code></pre>
<p>If possible, we want to avoid passing multiple props through components that don't need it.</p>
<p><em>What can we do?</em></p>
<p>Instead of immediately resorting to context because we are prop drilling, we should better compose our components.</p>
<p>Since only the top most component, <code>App</code>, needs to know about the <code>Avatar</code> component, we can create it directly within <code>App</code>.</p>
<p>This allows us to pass down a single prop, <code>avatar</code>, instead of two.</p>
<pre><code class="lang-js"><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">{ user }</span>) </span>{
  <span class="hljs-keyword">const</span> { username, avatarSrc } = user;

  <span class="hljs-keyword">const</span> avatar = <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">{avatarSrc}</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">{username}</span> /&gt;</span></span>;

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">main</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Navbar</span> <span class="hljs-attr">avatar</span>=<span class="hljs-string">{avatar}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span></span>
  );
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Navbar</span>(<span class="hljs-params">{ avatar }</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">nav</span>&gt;</span>{avatar}<span class="hljs-tag">&lt;/<span class="hljs-name">nav</span>&gt;</span></span>;
}
</code></pre>
<p><em>In short: don't reach for context right away. See if you can better organize your components to avoid prop drilling.</em></p>
<h2 id="heading-does-react-context-replace-redux">Does React context replace Redux?</h2>
<p>Yes and no.</p>
<p>For many React beginners, Redux is a way of more easily passing around data. This is because Redux comes with React context itself. </p>
<p>However, if you are not also <em>updating</em> state, but merely passing it down your component tree, you do not need a global state management library like Redux.</p>
<h2 id="heading-react-context-caveats">React context caveats</h2>
<p><em>Why it is not possible to update the value that React context passes down?</em></p>
<p>While it is possible to combine React context with a hook like useReducer and create a makeshift state management library without any third-party library, it is generally not recommended for performance reasons.</p>
<p>The issue with this approach lies in the way that React context triggers a re-render. </p>
<p>If you are passing down an object on your React context provider and any property on it updates, what happens? <em>Any component which consumes that context will re-render.</em></p>
<p>This may not be a performance issue in smaller apps with few state values that are not updated very often (such as theme data). But it is a problem if you will be performing many state updates in an application with a lot of components in your component tree.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I hope this guide gave you a better understanding of how to use React context from front to back.</p>
<p>If you want an even more in-depth grasp of how to use React context to build amazing React projects, check out <a target="_blank" href="https://www.thereactbootcamp.com">The React Bootcamp</a>.</p>
<h2 id="heading-become-a-professional-react-developer">Become a Professional React Developer</h2>
<p>React is hard. You shouldn't have to figure it out yourself.</p>
<p>I've put everything I know about React into a single course, to help you reach your goals in record time:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><strong>Introducing: The React Bootcamp</strong></a></p>
<p><strong>It’s the one course I wish I had when I started learning React.</strong></p>
<p>Click below to try the React Bootcamp for yourself:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><img src="https://reedbarger.nyc3.digitaloceanspaces.com/reactbootcamp/react-bootcamp-cta-alt.png" alt="Click to join the React Bootcamp" width="600" height="400" loading="lazy"></a>
<em>Click to get started</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Build a React Budget Tracker App – Learn React & Context API with this Fun Project ]]>
                </title>
                <description>
                    <![CDATA[ In this React Budget Tracker App tutorial we're going to: We’ll learn how break down a UI into React components Learn how to work with state using the Context API Learn about actions, reducers, and the dispatch function  And I’ll give you some chal... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-budget-tracker-app/</link>
                <guid isPermaLink="false">66c8c8fd85ffc69fd028a826</guid>
                
                    <category>
                        <![CDATA[ app development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ projects ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React context ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Chris Blakely ]]>
                </dc:creator>
                <pubDate>Fri, 12 Mar 2021 19:24:55 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/03/react-budget-app-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this React Budget Tracker App tutorial we're going to:</p>
<ul>
<li>We’ll learn how break down a UI into React components</li>
<li>Learn how to work with state using the Context API</li>
<li>Learn about actions, reducers, and the dispatch function </li>
</ul>
<p>And I’ll give you some challenges which you can try at the end!</p>
<h2 id="heading-this-is-what-well-build">This is what we'll build:</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screenshot-2021-03-07-at-09.20.33.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The user can:</p>
<ul>
<li>Add expenses which have a name and a cost</li>
<li>Remove expenses</li>
<li>View how much of their budget is remaining</li>
<li>View how much they've spent so far </li>
<li>(Challenge) Edit budget </li>
<li>(Challenge) Search expenses</li>
</ul>
<h2 id="heading-video-walkthrough">Video Walkthrough</h2>
<p><a target="_blank" href="https://youtu.be/aeYxBd1it7I">Heres a video walkthrough if you want to supplement your reading (on YouTube)</a></p>
<h2 id="heading-source-code">Source Code</h2>
<p>Finally, in case you get lost while following along, <a target="_blank" href="https://github.com/chrisblakely01/react-budget-app">you can grab the finished code here (on GitHub)</a>.</p>
<p>Let's Go!</p>
<h2 id="heading-how-to-setup-a-react-project">How to Setup a React Project</h2>
<p>The first thing we need to do is setup a React project. For this we'll use <code>create-react-app</code>. </p>
<p>Fire up a terminal and type:</p>
<p><code>npx create-react-app budget-tracker</code> </p>
<p>When that's finished doing its thing we're going to install Bootstrap. This will give us ready-made styles we can use instead of having to create our own in CSS. </p>
<p>In the same terminal, change to your working directory, and install Bootstrap:</p>
<pre><code>cd budget-tracker
npm i bootstrap
</code></pre><p>Next we're going to install a package that allows us to generate IDs. We'll be using IDs to identify each expense in the list, so this is important.</p>
<p>Run the following command in your project directory:</p>
<pre><code>npm i uuid
</code></pre><p>The last package we need to install gives us some icons to use, which saves us from having to create them ourselves.</p>
<p>Run the following command in your project directory:</p>
<pre><code>npm i react-icons
</code></pre><p>Now open up the project in VS Code (or whatever IDE you use). You should see some stuff appear in the project tree (this is our empty React project). </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screenshot-2021-03-07-at-09.37.55-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You can ignore most of this, as we'll be creating our own components. Open up App.js, delete everything, and add the following:</p>
<pre><code class="lang-jsx"><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> <span class="hljs-string">'bootstrap/dist/css/bootstrap.min.css'</span>;

<span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Hello React!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>What this does:</p>
<ul>
<li>Imports the bootstrap CSS into our project</li>
<li>Creates a component that displays "Hello React!" with paragraph tags</li>
<li>Exports this component so other components can use it</li>
</ul>
<p>Next we'll fire up the app and make sure everything is working as it should. Open a terminal (either in VS Code or otherwise) and start the app by typing the following:</p>
<pre><code>npm start
</code></pre><p>All being well, the app should start and open in a browser:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screenshot-2021-03-07-at-09.45.18.png" alt="Image" width="600" height="400" loading="lazy">
<em>The text "Hello React" should appear on the page. This means your app is working!</em></p>
<p>Success! Now we're ready to start building out our React components.</p>
<h2 id="heading-how-to-put-the-ui-components-in-place">How to Put the UI Components in Place</h2>
<p>One approach to building apps is to start by putting the UI components in place with some dummy data. This usually helps with visualising what state objects are needed, and usually means less rework later on. </p>
<p>With that in mind we're going to put our UI components in place starting at the top and working down. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screenshot-2021-03-07-at-10.04.55.png" alt="Image" width="600" height="400" loading="lazy">
<em>We'll add a title, then add a new component for each of the "boxes" shown. We'll add some dummy data just to get things displaying correctly</em></p>
<h3 id="heading-how-to-create-the-budget-component">How to Create the Budget Component</h3>
<p>Jump into the code, in the <strong>src</strong> folder, create a new folder called <strong>components.</strong> Within this, create a file called <strong>Budget.js.</strong> Your project structure should look like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screenshot-2021-03-07-at-10.13.37.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Open up <strong>Budget.js</strong> and add the following:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> Budget = <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">'alert alert-secondary'</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>Budget: £2000<span class="hljs-tag">&lt;/<span class="hljs-name">span</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> Budget;
</code></pre>
<p>What we're doing:</p>
<ul>
<li>Creating a new component called <strong>Budget</strong> (line 3)</li>
<li>Using the <strong>Bootstrap Alert</strong> classes to gives us a nice gray background (line 5)</li>
<li>Adding some text and hard coding a value (line 6)</li>
</ul>
<h3 id="heading-how-to-create-the-remaining-component">How to Create the <code>Remaining</code> Component</h3>
<p>Next we'll create the <strong><code>Remaining</code></strong> component, which shows how much budget the user has left.</p>
<p>Create a new file under <strong>src/components</strong> called <strong>Remaining.js</strong>. Open it up and add the following:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> Remaining = <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">'alert alert-success'</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>Remaining: £1000<span class="hljs-tag">&lt;/<span class="hljs-name">span</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> Remaining;
</code></pre>
<p>What we're doing:</p>
<ul>
<li>Creating a new component called <strong>Remaining</strong> (line 3)</li>
<li>Using the <strong>Bootstrap Alert</strong> classes to gives us a green background (line 5)</li>
<li>Adding some text and hard coding a value (line 6)</li>
<li>Adding Spent so Far</li>
</ul>
<p>Lastly, we'll create the <strong>Spent so Far</strong> component, which shows how much the user has spent so far.</p>
<p>Create a new file under <strong>src/components</strong> called <strong>ExpenseTotal.js</strong>. Open it up and add the following:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> ExpenseTotal = <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">'alert alert-primary'</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>Spent so far: £1000<span class="hljs-tag">&lt;/<span class="hljs-name">span</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> ExpenseTotal;
</code></pre>
<p>What we're doing:</p>
<ul>
<li>Creating a new component called <strong>ExpenseTotal</strong> (line 3)</li>
<li>Using the <strong>Bootstrap Alert</strong> classes to gives us a blue background (line 5)</li>
<li>Adding some text and hard coding a value (line 6)</li>
</ul>
<h3 id="heading-how-to-add-a-title-and-render-our-components">How to Add a Title and Render our Components</h3>
<p>At this point you might be thinking, "these components all look the same, what gives?!". This is true, although remember we're just adding some hard coded data for now. Later, each component will do different things to display the data dynamically.</p>
<p>Now we've created our components, we need to render them in <strong>App.js.</strong> Open App.js and add the following:</p>
<pre><code class="lang-jsx"><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> <span class="hljs-string">'bootstrap/dist/css/bootstrap.min.css'</span>;
<span class="hljs-keyword">import</span> Budget <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/Budget'</span>;
<span class="hljs-keyword">import</span> Remaining <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/Remaining'</span>;
<span class="hljs-keyword">import</span> ExpenseTotal <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/ExpenseTotal'</span>;

<span class="hljs-keyword">const</span> App = <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">'container'</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'mt-3'</span>&gt;</span>My Budget Planner<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">'row mt-3'</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'col-sm'</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">Budget</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">'col-sm'</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">Remaining</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">'col-sm'</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">ExpenseTotal</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> App;
</code></pre>
<p>What we're doing:</p>
<ul>
<li>Importing our different components (lines 3-5)</li>
<li>Adding a bootstrap container that helps us center our App on the page (line 9)</li>
<li>Adding a title (line 9)</li>
<li>Adding a Bootstrap row (line 10)</li>
<li>Adding a column within the row for each of our components so far (lines 12-20)</li>
</ul>
<p>Now if you run the app, you should see the title, and our components rendered on the page!</p>
<h3 id="heading-how-to-create-the-expense-list-component">How to Create the Expense List Component</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screenshot-2021-03-07-at-10.31.44.png" alt="Image" width="600" height="400" loading="lazy">
<em>The expenses list shows the expenses the user has added so far, displaying the Name, cost, and a delete button for each</em></p>
<p>Next we'll build the <strong>ExpenseList</strong> component. This component will be in charge of taking a list of expenses, and rendering an <strong>ExpenseItem</strong> component for each item. </p>
<p>We'll add some dummy data, to make sure our UI looks good and things are working as intended. Later, this stuff will come from context.</p>
<p>Start by creating a new file under <strong>src/components</strong> called <strong>ExpenseList.js</strong>. Open up ExpenseList.js and add the following:</p>
<pre><code class="lang-jsx"><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> ExpenseItem <span class="hljs-keyword">from</span> <span class="hljs-string">'./ExpenseItem'</span>;

<span class="hljs-keyword">const</span> ExpenseList = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> expenses = [
        { <span class="hljs-attr">id</span>: <span class="hljs-number">12</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'shopping'</span>, <span class="hljs-attr">cost</span>: <span class="hljs-number">40</span> },
        { <span class="hljs-attr">id</span>: <span class="hljs-number">13</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'holiday'</span>, <span class="hljs-attr">cost</span>: <span class="hljs-number">400</span> },
        { <span class="hljs-attr">id</span>: <span class="hljs-number">14</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'car service'</span>, <span class="hljs-attr">cost</span>: <span class="hljs-number">50</span> },
    ];

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'list-group'</span>&gt;</span>
            {expenses.map((expense) =&gt; (
                <span class="hljs-tag">&lt;<span class="hljs-name">ExpenseItem</span> <span class="hljs-attr">id</span>=<span class="hljs-string">{expense.id}</span> <span class="hljs-attr">name</span>=<span class="hljs-string">{expense.name}</span> <span class="hljs-attr">cost</span>=<span class="hljs-string">{expense.cost}</span> /&gt;</span>
            ))}
        <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span></span>
    )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ExpenseList
</code></pre>
<p>What we're doing:</p>
<ul>
<li>Adding a dummy list of expenses. For each expense we need an ID, a name, and a cost. Later, we'll take this list from context (line 4)</li>
<li>Creating a list (line 11)</li>
<li>Using the map function to iterate over the expenses and displaying an ExpenseItem component (we haven't created this yet! Line 12)</li>
<li>Passing the ID, name, and cost to the ExpenseItem component as props</li>
</ul>
<h3 id="heading-how-to-create-the-expense-item-component">How to Create the Expense Item Component</h3>
<p>Now we've created a component to hold our list, we need a component to render each item. Create a new file in the <strong>src/components</strong> folder called <strong>ExpenseItem.js.</strong> Open it up and add the following:</p>
<pre><code class="lang-jsx"><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> { TiDelete } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-icons/ti'</span>;

<span class="hljs-keyword">const</span> ExpenseItem = <span class="hljs-function">(<span class="hljs-params">props</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'list-group-item d-flex justify-content-between align-items-center'</span>&gt;</span>
            {props.name}
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'badge badge-primary badge-pill mr-3'</span>&gt;</span>
                    £{props.cost}
                <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">TiDelete</span> <span class="hljs-attr">size</span>=<span class="hljs-string">'1.5em'</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">TiDelete</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">li</span>&gt;</span></span>
    );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ExpenseItem;
</code></pre>
<p>What we're doing:</p>
<ul>
<li>Creating a list item (line 6)</li>
<li>Rendering the name of the expense, which we get from props (line 7)</li>
<li>Rendering the cost of the expense, which we also get from props</li>
<li>We're displaying a DeleteIcon (line 12) which we get from react-icons package (line 2)</li>
</ul>
<h3 id="heading-how-to-render-the-expenselist-component">How to Render the ExpenseList Component</h3>
<p>Now we've created our components, we just have to render ExpenseList in App.js. Open up App.js and update it with the following:</p>
<pre><code class="lang-jsx"><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> <span class="hljs-string">'bootstrap/dist/css/bootstrap.min.css'</span>;
<span class="hljs-keyword">import</span> Budget <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/Budget'</span>;
<span class="hljs-keyword">import</span> Remaining <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/Remaining'</span>;
<span class="hljs-keyword">import</span> ExpenseTotal <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/ExpenseTotal'</span>;
<span class="hljs-keyword">import</span> ExpenseList <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/ExpenseList'</span>;

<span class="hljs-keyword">const</span> App = <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">'container'</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'mt-3'</span>&gt;</span>My Budget Planner<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">'row mt-3'</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'col-sm'</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">Budget</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">'col-sm'</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">Remaining</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">'col-sm'</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">ExpenseTotal</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">h3</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'mt-3'</span>&gt;</span>Expenses<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'row mt-3'</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'col-sm'</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">ExpenseList</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> App;
</code></pre>
<p>What's new:</p>
<ul>
<li>We imported our ExpenseList (line 6)</li>
<li>Added a new Bootstrap row (line 24)</li>
<li>Rendered our ExpenseList (line 26)</li>
</ul>
<p>Now if you save/run the App, you'll see the Expenses list has appeared!</p>
<h3 id="heading-how-to-create-the-add-expense-form-component">How to create the "Add Expense" form component</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Screenshot-2021-03-08-at-07.28.29.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Our UI components are nearly complete! The last component we need is the "Add Expense" form component, which lets users add new expenses. We'll put the UI components for the form in place first, then come back later and add the fancy stuff.</p>
<p>Create a new file in <strong>src/components</strong> called <strong>AddExpenseForm.js</strong>. Fire this up and add the following:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> AddExpenseForm = <span class="hljs-function">() =&gt;</span> {

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'row'</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'col-sm'</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">'name'</span>&gt;</span>Name<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
                        <span class="hljs-attr">required</span>=<span class="hljs-string">'required'</span>
                        <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span>
                        <span class="hljs-attr">className</span>=<span class="hljs-string">'form-control'</span>
                        <span class="hljs-attr">id</span>=<span class="hljs-string">'name'</span>
                    &gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">input</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">'col-sm'</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">'cost'</span>&gt;</span>Cost<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
                        <span class="hljs-attr">required</span>=<span class="hljs-string">'required'</span>
                        <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span>
                        <span class="hljs-attr">className</span>=<span class="hljs-string">'form-control'</span>
                        <span class="hljs-attr">id</span>=<span class="hljs-string">'cost'</span>
                    &gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">input</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> <span class="hljs-attr">className</span>=<span class="hljs-string">'row'</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'col-sm'</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'submit'</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'btn btn-primary mt-3'</span>&gt;</span>
                        Save
                    <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 class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
    );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> AddExpenseForm;
</code></pre>
<p>What we're doing:</p>
<ul>
<li>Adding our form tags (line 6)</li>
<li>Adding a label/input for our <strong>name</strong> field (line 9)</li>
<li>Adding a label/input for our <strong>cost</strong> field (line 18)</li>
<li>Adding a button to submit the form (line 30)</li>
</ul>
<h3 id="heading-how-to-render-the-addexpenseform-component">How to Render the AddExpenseForm component</h3>
<p>Finally in App.js, we have to render our new component. Update App.js with the following:</p>
<pre><code><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> <span class="hljs-string">'bootstrap/dist/css/bootstrap.min.css'</span>;
<span class="hljs-keyword">import</span> Budget <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/Budget'</span>;
<span class="hljs-keyword">import</span> Remaining <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/Remaining'</span>;
<span class="hljs-keyword">import</span> ExpenseTotal <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/ExpenseTotal'</span>;
<span class="hljs-keyword">import</span> ExpenseList <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/ExpenseList'</span>;
<span class="hljs-keyword">import</span> AddExpenseForm <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/AddExpenseForm'</span>;

<span class="hljs-keyword">const</span> App = <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">'container'</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'mt-3'</span>&gt;</span>My Budget Planner<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">'row mt-3'</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'col-sm'</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">Budget</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">'col-sm'</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">Remaining</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">'col-sm'</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">ExpenseTotal</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">h3</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'mt-3'</span>&gt;</span>Expenses<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'row mt-3'</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'col-sm'</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">ExpenseList</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">h3</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'mt-3'</span>&gt;</span>Add Expense<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'row mt-3'</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'col-sm'</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">AddExpenseForm</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> App;
</code></pre><p>What's changed:</p>
<ul>
<li>Imported the AddExpenseForm (line 7)</li>
<li>Rendered the AddExpenseForm (line 33)</li>
</ul>
<h2 id="heading-how-to-add-the-context-api">How to Add the Context API</h2>
<p>The Context API is what we'll use to store our global state. It's already part of the React library so no need to import/install anything else.</p>
<p>Start by creating a new folder in the <strong>src</strong> folder called <strong>context.</strong> Within this folder create a new file called <strong>AppContext.js.</strong></p>
<h3 id="heading-how-to-create-the-initial-state">How to Create the Initial State</h3>
<p>The first thing our context needs to work is an initial state. This indicates the "shape" of our state (in other words, what properties and data we have) and can be used to initialise the app with data from an API call, for example.</p>
<p>For now we'll just add some initial values. In AppContext.js, add the following:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> initialState = {
    <span class="hljs-attr">budget</span>: <span class="hljs-number">2000</span>,
    <span class="hljs-attr">expenses</span>: [
        { <span class="hljs-attr">id</span>: <span class="hljs-number">12</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'shopping'</span>, <span class="hljs-attr">cost</span>: <span class="hljs-number">40</span> },
        { <span class="hljs-attr">id</span>: <span class="hljs-number">13</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'holiday'</span>, <span class="hljs-attr">cost</span>: <span class="hljs-number">400</span> },
        { <span class="hljs-attr">id</span>: <span class="hljs-number">14</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'car service'</span>, <span class="hljs-attr">cost</span>: <span class="hljs-number">50</span> },
    ],
};
</code></pre>
<ul>
<li>We're adding an initial budget</li>
<li>We're adding a dummy list of expenses</li>
</ul>
<blockquote>
<p>NOTE: the intialState properties do not need to have values, they can be set to empty strings, empty arrays, and so on. We're adding data for visual purposes</p>
</blockquote>
<h3 id="heading-how-to-create-the-appcontext">How to Create the AppContext</h3>
<p>Next we'll create the AppContext. This is the thing our components import and use to get the state. </p>
<p>Update AppContext.js with the following:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> initialState = {
    <span class="hljs-attr">budget</span>: <span class="hljs-number">2000</span>,
    <span class="hljs-attr">expenses</span>: [
        { <span class="hljs-attr">id</span>: <span class="hljs-number">12</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'shopping'</span>, <span class="hljs-attr">cost</span>: <span class="hljs-number">40</span> },
        { <span class="hljs-attr">id</span>: <span class="hljs-number">13</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'holiday'</span>, <span class="hljs-attr">cost</span>: <span class="hljs-number">400</span> },
        { <span class="hljs-attr">id</span>: <span class="hljs-number">14</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'car service'</span>, <span class="hljs-attr">cost</span>: <span class="hljs-number">50</span> },
    ],
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> AppContext = createContext();
</code></pre>
<p>All we've done is added a call to createContext at line (11) - thats our context object created! </p>
<h3 id="heading-how-to-create-the-appprovider">How to Create the AppProvider</h3>
<p>The provider is a component that wraps the components which we want to pass the state to. We use it in conjunction with the useReducer hook to actually store the global state.</p>
<p>Update the AppContext.js file like so:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> initialState = {
    <span class="hljs-attr">budget</span>: <span class="hljs-number">2000</span>,
    <span class="hljs-attr">expenses</span>: [
        { <span class="hljs-attr">id</span>: <span class="hljs-number">12</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'shopping'</span>, <span class="hljs-attr">cost</span>: <span class="hljs-number">40</span> },
        { <span class="hljs-attr">id</span>: <span class="hljs-number">13</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'holiday'</span>, <span class="hljs-attr">cost</span>: <span class="hljs-number">400</span> },
        { <span class="hljs-attr">id</span>: <span class="hljs-number">14</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'car service'</span>, <span class="hljs-attr">cost</span>: <span class="hljs-number">50</span> },
    ],
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> AppContext = createContext();

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> AppProvider = <span class="hljs-function">(<span class="hljs-params">props</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> [state, dispatch] = useReducer(AppReducer, initialState);

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">AppContext.Provider</span>
            <span class="hljs-attr">value</span>=<span class="hljs-string">{{</span>
                <span class="hljs-attr">budget:</span> <span class="hljs-attr">state.budget</span>,
                <span class="hljs-attr">expenses:</span> <span class="hljs-attr">state.expenses</span>,
                <span class="hljs-attr">dispatch</span>,
            }}
        &gt;</span>
            {props.children}
        <span class="hljs-tag">&lt;/<span class="hljs-name">AppContext.Provider</span>&gt;</span></span>
    );
};
</code></pre>
<p>What we're doing:</p>
<ul>
<li>Creating our Provider component (line 12)</li>
<li>Setting up the useReducer hook which will hold our state, and allow us to update the state via dispatch (NOTE we haven't created the AppReducer yet! Line 13)</li>
<li>We're returning <strong>AppContext.Provider.</strong> This has a <strong>value</strong> prop which contains the data which we allow our components to see and have access to, as well as the dispatch function that lets us update the state by dispatching actions (line 16)</li>
</ul>
<h3 id="heading-how-to-create-the-appreducer">How to Create the AppReducer</h3>
<p>Next we’ll create the AppReducer. The reducer is in charge of creating the new global state object, based on an action type and a payload. </p>
<p>Update AppContext.js with the following:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> AppReducer = <span class="hljs-function">(<span class="hljs-params">state, action</span>) =&gt;</span> {
    <span class="hljs-keyword">switch</span> (action.type) {
        <span class="hljs-attr">default</span>:
            <span class="hljs-keyword">return</span> state;
    }
};

<span class="hljs-keyword">const</span> initialState = {
    <span class="hljs-attr">budget</span>: <span class="hljs-number">2000</span>,
    <span class="hljs-attr">expenses</span>: [
        { <span class="hljs-attr">id</span>: <span class="hljs-number">12</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'shopping'</span>, <span class="hljs-attr">cost</span>: <span class="hljs-number">40</span> },
        { <span class="hljs-attr">id</span>: <span class="hljs-number">13</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'holiday'</span>, <span class="hljs-attr">cost</span>: <span class="hljs-number">400</span> },
        { <span class="hljs-attr">id</span>: <span class="hljs-number">14</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'car service'</span>, <span class="hljs-attr">cost</span>: <span class="hljs-number">50</span> },
    ],
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> AppContext = createContext();

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> AppProvider = <span class="hljs-function">(<span class="hljs-params">props</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> [state, dispatch] = useReducer(AppReducer, initialState);

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">AppContext.Provider</span>
            <span class="hljs-attr">value</span>=<span class="hljs-string">{{</span>
                <span class="hljs-attr">budget:</span> <span class="hljs-attr">state.budget</span>,
                <span class="hljs-attr">expenses:</span> <span class="hljs-attr">state.expenses</span>,
                <span class="hljs-attr">dispatch</span>,
            }}
        &gt;</span>
            {props.children}
        <span class="hljs-tag">&lt;/<span class="hljs-name">AppContext.Provider</span>&gt;</span></span>
    );
};
</code></pre>
<p>What we're doing:</p>
<ul>
<li>Creating a function which accepts the current state, and an action (line 1)</li>
<li>We use a switch based on the action.type to decide how to update the state (line 2)</li>
<li>For now since we’re just getting things set up we’re just going to return the default state, and add actions later as we need them (line 3)</li>
</ul>
<p>And thats it! Our global state is now set up and ready to go. </p>
<h2 id="heading-how-to-link-appcontext-to-our-app">How to Link AppContext to our App</h2>
<p>The next step is to link our AppContext to our App component. We do this by wrapping the components which we want to pass the state to with the AppProvider.</p>
<p>Jump back into App.js and update the following:</p>
<pre><code class="lang-jsx"><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> <span class="hljs-string">'bootstrap/dist/css/bootstrap.min.css'</span>;
<span class="hljs-keyword">import</span> Budget <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/Budget'</span>;
<span class="hljs-keyword">import</span> Remaining <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/Remaining'</span>;
<span class="hljs-keyword">import</span> ExpenseTotal <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/ExpenseTotal'</span>;
<span class="hljs-keyword">import</span> ExpenseList <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/ExpenseList'</span>;
<span class="hljs-keyword">import</span> AddExpenseForm <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/AddExpenseForm'</span>;
<span class="hljs-keyword">import</span> { AppProvider } <span class="hljs-keyword">from</span> <span class="hljs-string">'./context/AppContext'</span>;

<span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">AppProvider</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'container'</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'mt-3'</span>&gt;</span>My Budget Planner<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">'row mt-3'</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'col-sm'</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">Budget</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">'col-sm'</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">Remaining</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">'col-sm'</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">ExpenseTotal</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">h3</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'mt-3'</span>&gt;</span>Expenses<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'row mt-3'</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'col-sm'</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">ExpenseList</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">h3</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'mt-3'</span>&gt;</span>Add Expense<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'row mt-3'</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'col-sm'</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">AddExpenseForm</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 class="hljs-tag">&lt;/<span class="hljs-name">AppProvider</span>&gt;</span></span>
    );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>What's changed:</p>
<ul>
<li>Imported our <strong>AppProvider</strong> (line 8)</li>
<li>Nested our components in the AppProvider element (lines 12 / lines 39)</li>
</ul>
<p>Now that our components are nested within the AppProvider, they have access to <strong>value</strong> object that the AppProvider exposes. </p>
<h2 id="heading-how-to-connect-our-components-to-appcontext">How to Connect our Components to AppContext</h2>
<h3 id="heading-how-to-render-budget-from-context">How to Render Budget from Context</h3>
<p>Now we can start pulling global state values into our components. We'll start with the budget, so jump into <strong>Budget.js</strong> and add the following:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { AppContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'../context/AppContext'</span>;

<span class="hljs-keyword">const</span> Budget = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> { budget } = useContext(AppContext);

    <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">'alert alert-secondary'</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>Budget: £{budget}<span class="hljs-tag">&lt;/<span class="hljs-name">span</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> Budget;
</code></pre>
<p>What we're doing:</p>
<ul>
<li>We have to import <strong>AppContext</strong> from our Context (line 2)</li>
<li>We import the <strong>useContext</strong> hook, and pass our AppContext to it -  this is how a component connects to the context in order to get values from global state</li>
<li>We use <strong>destructuring</strong> to get the <strong>budget</strong> from context (line 5)</li>
<li>We're rendering the budget in our JSX (line 9)</li>
</ul>
<p>Now if you change the budget in AppContext and reload your browser, you will see the budget updates on the UI. This means our component is successfully pulling data from our context. Success! </p>
<h3 id="heading-how-to-render-expenses-from-context">How to Render Expenses from Context</h3>
<p>Now we can do something similar with the expense list. Open up <strong>ExpenseList.js</strong> and update it with the following:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> ExpenseItem <span class="hljs-keyword">from</span> <span class="hljs-string">'./ExpenseItem'</span>;
<span class="hljs-keyword">import</span> { AppContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'../context/AppContext'</span>;

<span class="hljs-keyword">const</span> ExpenseList = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> { expenses } = useContext(AppContext);

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'list-group'</span>&gt;</span>
            {expenses.map((expense) =&gt; (
                <span class="hljs-tag">&lt;<span class="hljs-name">ExpenseItem</span> <span class="hljs-attr">id</span>=<span class="hljs-string">{expense.id}</span> <span class="hljs-attr">name</span>=<span class="hljs-string">{expense.name}</span> <span class="hljs-attr">cost</span>=<span class="hljs-string">{expense.cost}</span> /&gt;</span>
            ))}
        <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span></span>
    );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ExpenseList;
</code></pre>
<p>What we're doing:</p>
<ul>
<li>Importing our AppContext and useContext hook like before </li>
<li>We've removed the dummy list of expenses</li>
<li>We've replaced the dummy list with the expenses list we store in context</li>
</ul>
<p>Since we've already done the work to render the list of expenses, we don't have to do anything else! Refresh the browser and you'll see the list now comes from context rather than the dummy list.</p>
<p>Remember we exported expenses as part of the value object in the provider. Any component wrapped in the provider can get access to this value object, and use destructuring to get the specific value it needs.</p>
<h3 id="heading-how-to-add-a-new-expense-capturing-form-values">How to Add a New Expense - Capturing Form Values</h3>
<p>So far we've looked at how to get values from state, next we'll look at how we can dispatch actions and update the state.</p>
<p>Before we do that, we need to know the <strong>name</strong> and the <strong>cost</strong> of the new expense that the user has entered. Jump into AddExpenseForm.js and add the following:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> AddExpenseForm = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> [name, setName] = useState(<span class="hljs-string">''</span>);
    <span class="hljs-keyword">const</span> [cost, setCost] = useState(<span class="hljs-string">''</span>);

    <span class="hljs-keyword">const</span> onSubmit = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {

    };

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{onSubmit}</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'row'</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'col-sm'</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">'name'</span>&gt;</span>Name<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
                        <span class="hljs-attr">required</span>=<span class="hljs-string">'required'</span>
                        <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span>
                        <span class="hljs-attr">className</span>=<span class="hljs-string">'form-control'</span>
                        <span class="hljs-attr">id</span>=<span class="hljs-string">'name'</span>
                        <span class="hljs-attr">value</span>=<span class="hljs-string">{name}</span>
                        <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(event)</span> =&gt;</span> setName(event.target.value)}
                    &gt;<span class="hljs-tag">&lt;/<span class="hljs-name">input</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">'col-sm'</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">'cost'</span>&gt;</span>Cost<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
                        <span class="hljs-attr">required</span>=<span class="hljs-string">'required'</span>
                        <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span>
                        <span class="hljs-attr">className</span>=<span class="hljs-string">'form-control'</span>
                        <span class="hljs-attr">id</span>=<span class="hljs-string">'cost'</span>
                        <span class="hljs-attr">value</span>=<span class="hljs-string">{cost}</span>
                        <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(event)</span> =&gt;</span> setCost(event.target.value)}
                    &gt;<span class="hljs-tag">&lt;/<span class="hljs-name">input</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">'col-sm'</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'submit'</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'btn btn-primary mt-3'</span>&gt;</span>
                        Save
                    <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 class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
    );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> AddExpenseForm;
</code></pre>
<p>What we're doing:</p>
<ul>
<li>Using React to control the <strong>input values</strong>. For each input field, we have a state object (lines 7 and 8)</li>
<li>When the user types into the inputs, the corresponding state values will update (lines 25 and 36)</li>
<li>When the user clicks the button, it will call an <strong>onSubmit</strong> function. This function doesn't do anything right now, but this is where we'll dispatch the action from</li>
</ul>
<p>Now we have the form values stored in state, we can dispatch an action to update the state.</p>
<h3 id="heading-how-to-add-a-new-expense-dispatching-an-action">How to Add a New Expense - Dispatching an action</h3>
<p>Update the AddExpenseForm with the following:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { useContext, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { AppContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'../context/AppContext'</span>;
<span class="hljs-keyword">import</span> { v4 <span class="hljs-keyword">as</span> uuidv4 } <span class="hljs-keyword">from</span> <span class="hljs-string">'uuid'</span>;

<span class="hljs-keyword">const</span> AddExpenseForm = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> { dispatch } = useContext(AppContext);

    <span class="hljs-keyword">const</span> [name, setName] = useState(<span class="hljs-string">''</span>);
    <span class="hljs-keyword">const</span> [cost, setCost] = useState(<span class="hljs-string">''</span>);

    <span class="hljs-keyword">const</span> onSubmit = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
        event.preventDefault();

        <span class="hljs-keyword">const</span> expense = {
            <span class="hljs-attr">id</span>: uuidv4(),
            <span class="hljs-attr">name</span>: name,
            <span class="hljs-attr">cost</span>: <span class="hljs-built_in">parseInt</span>(cost),
        };

        dispatch({
            <span class="hljs-attr">type</span>: <span class="hljs-string">'ADD_EXPENSE'</span>,
            <span class="hljs-attr">payload</span>: expense,
        });
    };

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{onSubmit}</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'row'</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'col-sm'</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">'name'</span>&gt;</span>Name<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
                        <span class="hljs-attr">required</span>=<span class="hljs-string">'required'</span>
                        <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span>
                        <span class="hljs-attr">className</span>=<span class="hljs-string">'form-control'</span>
                        <span class="hljs-attr">id</span>=<span class="hljs-string">'name'</span>
                        <span class="hljs-attr">value</span>=<span class="hljs-string">{name}</span>
                        <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(event)</span> =&gt;</span> setName(event.target.value)}
                    &gt;<span class="hljs-tag">&lt;/<span class="hljs-name">input</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">'col-sm'</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">'cost'</span>&gt;</span>Cost<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
                        <span class="hljs-attr">required</span>=<span class="hljs-string">'required'</span>
                        <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span>
                        <span class="hljs-attr">className</span>=<span class="hljs-string">'form-control'</span>
                        <span class="hljs-attr">id</span>=<span class="hljs-string">'cost'</span>
                        <span class="hljs-attr">value</span>=<span class="hljs-string">{cost}</span>
                        <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(event)</span> =&gt;</span> setCost(event.target.value)}
                    &gt;<span class="hljs-tag">&lt;/<span class="hljs-name">input</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">'col-sm'</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'submit'</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'btn btn-primary mt-3'</span>&gt;</span>
                        Save
                    <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 class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
    );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> AddExpenseForm;
</code></pre>
<p>What we're doing:</p>
<ul>
<li>Importing AppContext and useContext as usual </li>
<li>Getting <strong>dispatch</strong> from our global state (line 6)</li>
<li>Creating an <strong>expense object,</strong> containing the name and the cost. This is what will get dispatched as the payload, and what we'll use to update the state. We're also using the uuid package we imported earlier to create an ID. This is used to identify a given expense (line 14).</li>
<li>We're dispatching an <strong>action</strong>, with a type and our payload. The type tells the reducer how to update the state, which we'll see in a minute (line 20)</li>
</ul>
<h3 id="heading-how-to-add-a-new-expense-updating-the-reducer">How to Add a New Expense - Updating the reducer</h3>
<p>That's it from the component side. You'll notice if you run this in the browser, nothing happens. Thats because we haven't updated our reducer to handle the action and update the state. </p>
<p>Jump into <strong>AppContext.js</strong> and update the <strong>reducer</strong> function with the following:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> AppReducer = <span class="hljs-function">(<span class="hljs-params">state, action</span>) =&gt;</span> {
    <span class="hljs-keyword">switch</span> (action.type) {
        <span class="hljs-keyword">case</span> <span class="hljs-string">'ADD_EXPENSE'</span>:
            <span class="hljs-keyword">return</span> {
                ...state,
                <span class="hljs-attr">expenses</span>: [...state.expenses, action.payload],
            };
        <span class="hljs-keyword">default</span>:
            <span class="hljs-keyword">return</span> state;
    }
};
</code></pre>
<p>What we're doing:</p>
<ul>
<li>We're checking the type of the action (which we get from the action variable) (line 2)</li>
<li>Adding a new case to the switch statement called "ADD_EXPENSE" (line 3)</li>
<li>Returning a new state object with the new expense taking from the payload (which we get from the action variable) (line 4)</li>
</ul>
<blockquote>
<p>When we return something from a case statement, the reducer automatically updates the state and re-renders the components, almost like magic.</p>
</blockquote>
<p>Now if you run the code, and add a new expense, you can see it gets added to the expense list!</p>
<h3 id="heading-how-to-calculate-spent-so-far">How to Calculate <code>spent so far</code></h3>
<p>The next thing we'll look at is calculating how much the user has spent so far. To do this, we'll take a total of all the expenses the user has spent and display it on the UI.</p>
<p>Open up <strong>ExpenseTotal.js</strong>  and update it with the following:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { AppContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'../context/AppContext'</span>;

<span class="hljs-keyword">const</span> ExpenseTotal = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> { expenses } = useContext(AppContext);

    <span class="hljs-keyword">const</span> totalExpenses = expenses.reduce(<span class="hljs-function">(<span class="hljs-params">total, item</span>) =&gt;</span> {
        <span class="hljs-keyword">return</span> (total += item.cost);
    }, <span class="hljs-number">0</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">'alert alert-primary'</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>Spent so far: £{totalExpenses}<span class="hljs-tag">&lt;/<span class="hljs-name">span</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> ExpenseTotal;
</code></pre>
<p>What we're doing:</p>
<ul>
<li>importing our useContext and AppContext as usual </li>
<li>Taking the expenses from state (line 5)</li>
<li>Using the reduce function to get a total of all the costs and assigning this to a variable (line 7)</li>
<li>Displaying the variable in our JSX (line 13)</li>
</ul>
<p>Now whenever the user adds an expense, this causes the state to update, which will cause all components connected to the context to re-render and update themselves with new values.</p>
<p>Go ahead and try this out in the browser.</p>
<h3 id="heading-how-to-calculate-remaining">How to Calculate <code>Remaining</code></h3>
<p>Now we'll look at calculating how much budget the user has left to spend. </p>
<p>To do this, we'll get the total costs of the expenses, and subtract it from the budget. If the user goes over budget, i.e the expenses are more than the budget, we want to display a red background (as opposed to a green background). Luckily Bootstrap gives us these nice things already.</p>
<p>Open up Remaining.js and update it with the following:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { AppContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'../context/AppContext'</span>;

<span class="hljs-keyword">const</span> Remaining = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> { expenses, budget } = useContext(AppContext);

    <span class="hljs-keyword">const</span> totalExpenses = expenses.reduce(<span class="hljs-function">(<span class="hljs-params">total, item</span>) =&gt;</span> {
        <span class="hljs-keyword">return</span> (total = total + item.cost);
    }, <span class="hljs-number">0</span>);

    <span class="hljs-keyword">const</span> alertType = totalExpenses &gt; budget ? <span class="hljs-string">'alert-danger'</span> : <span class="hljs-string">'alert-success'</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">{</span>`<span class="hljs-attr">alert</span> ${<span class="hljs-attr">alertType</span>}`}&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>Remaining: £{budget - totalExpenses}<span class="hljs-tag">&lt;/<span class="hljs-name">span</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> Remaining;
</code></pre>
<p>What we're doing</p>
<ul>
<li>Importing expenses and budget from Context (line 5)</li>
<li>Getting the total cost of the expenses using the reduce function (line 7)</li>
<li>Creating a variable to store the CSS classname we want to display (depending on if the user has gone over the budget or not, line 11)</li>
<li>Using a template string to create our classes (line 14)</li>
<li>Rendering the remaining budget using a subtraction (line 15)</li>
</ul>
<p>Now if you run the code in the browser, and add a bunch of expenses until the total goes over 2000, you'll see the "Remaining" component background turns to red!</p>
<h3 id="heading-how-to-remove-an-expense">How to Remove an Expense</h3>
<p>The last thing we'll look at before getting into the challenges is to remove an expense. </p>
<p>When the user clicks the little cross beside an expense, we want to dispatch an action to remove it from state. When this happens, our ExpenseList will re-render with the removed expense.</p>
<p>Jump into ExpenseItem.js and update it with the following:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { TiDelete } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-icons/ti'</span>;
<span class="hljs-keyword">import</span> { AppContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'../context/AppContext'</span>;

<span class="hljs-keyword">const</span> ExpenseItem = <span class="hljs-function">(<span class="hljs-params">props</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> { dispatch } = useContext(AppContext);

    <span class="hljs-keyword">const</span> handleDeleteExpense = <span class="hljs-function">() =&gt;</span> {
        dispatch({
            <span class="hljs-attr">type</span>: <span class="hljs-string">'DELETE_EXPENSE'</span>,
            <span class="hljs-attr">payload</span>: props.id,
        });
    };

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'list-group-item d-flex justify-content-between align-items-center'</span>&gt;</span>
            {props.name}
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'badge badge-primary badge-pill mr-3'</span>&gt;</span>
                    £{props.cost}
                <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">TiDelete</span> <span class="hljs-attr">size</span>=<span class="hljs-string">'1.5em'</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleDeleteExpense}</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">TiDelete</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">li</span>&gt;</span></span>
    );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ExpenseItem;
</code></pre>
<p>What we're doing:</p>
<ul>
<li>Importing dispatch from Context, which allows us to dispatch a delete action (line 6)</li>
<li>Creating a function that gets called when the delete icon is clicked (line 8)</li>
<li>Dispatching an action. Our action contains the type (so the reducer knows how to update the state) and the payload. In this case we're passing the ID of this expense (which we get from props when we rendered the ExpenseList) (line 9)</li>
</ul>
<p>If you try this in the browser, you'll see that nothing happens. Even though we're dispatching an action, we haven't implemented the reducer logic for this action type, so it doesn't know how to update the state.</p>
<p>Jump into AppContext.js and update the reducer function with the following:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> AppReducer = <span class="hljs-function">(<span class="hljs-params">state, action</span>) =&gt;</span> {
    <span class="hljs-keyword">switch</span> (action.type) {
        <span class="hljs-keyword">case</span> <span class="hljs-string">'ADD_EXPENSE'</span>:
            <span class="hljs-keyword">return</span> {
                ...state,
                <span class="hljs-attr">expenses</span>: [...state.expenses, action.payload],
            };
        <span class="hljs-keyword">case</span> <span class="hljs-string">'DELETE_EXPENSE'</span>:
            <span class="hljs-keyword">return</span> {
                ...state,
                <span class="hljs-attr">expenses</span>: state.expenses.filter(
                    <span class="hljs-function">(<span class="hljs-params">expense</span>) =&gt;</span> expense.id !== action.payload
                ),
            };
        <span class="hljs-keyword">default</span>:
            <span class="hljs-keyword">return</span> state;
    }
};
</code></pre>
<p>All we're really doing here is adding a new case statement, to handle our <strong>DELETE_EXPENSE</strong> action. We're using the filter array method to remove the expense that has the ID which we received from the payload.</p>
<p>Now if you try this, you can remove an expense by clicking the delete icon. Notice how all the other components update as well. Nice!</p>
<h2 id="heading-challenges-to-try">Challenges to Try</h2>
<p>Congrats on making it this far! Now its time for you to have a go at some challenges. Remember you can see how I've done it in the GitHub source code.</p>
<h3 id="heading-allow-the-user-to-edit-the-budget">Allow the user to edit the budget</h3>
<p>You'll notice that so far we have been using a hard coded value for the budget. Your first task is to add functionality that allows the user to edit the budget. Some tips to get started:</p>
<ul>
<li>You will need to add a text input that allows the user to enter a value for their desired budget.</li>
<li>We store the budget in state, so you will need to dispatch an action with a new TYPE and a PAYLOAD that will update the state </li>
</ul>
<h3 id="heading-allow-the-user-to-search-for-an-expense">Allow the user to search for an expense</h3>
<p>If the user has many expenses, it will be difficult to find the one they are looking for. Add a way for the user to search for the expense by name. Some tips to get started:</p>
<ul>
<li>You will need to add an input field which lets the user enter a value to search for. </li>
<li>You'll have to add something to the ExpenseList component that filters the list from context based on this search value. </li>
</ul>
<h3 id="heading-thanks-for-reading">Thanks for Reading!</h3>
<p><a target="_blank" href="https://reactbeginnerprojects.com"><img src="https://www.freecodecamp.org/news/content/images/size/w1000/2021/03/Screenshot-2021-03-10-at-08.33.56.png" alt="Screenshot-2021-03-10-at-08.33.56" width="600" height="400" loading="lazy"></a> </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Learn React in 2021: The 7 Skills You Need To Know ]]>
                </title>
                <description>
                    <![CDATA[ You want to learn React_—_the most in-demand JavaScript library in the world. But what steps do you need to take to get there? Let's walk through the seven skills you should learn to become a professional React developer. As you're piecing together y... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-learn-react-skills-you-need-to-know/</link>
                <guid isPermaLink="false">66d0378415ea3036a9539941</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React context ]]>
                    </category>
                
                    <category>
                        <![CDATA[ react hooks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ react router ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Reed ]]>
                </dc:creator>
                <pubDate>Wed, 06 Jan 2021 16:01:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/01/how-to-learn-react-2021-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>You want to learn React_—_the most in-demand JavaScript library in the world. But what steps do you need to take to get there? Let's walk through the seven skills you should learn to become a professional React developer.</p>
<p>As you're piecing together your React learning path, it's easy to feel overwhelmed and say, <em>"It's impossible to learn it all. There are too many things I need to learn!"</em></p>
<p><strong>To be successful with React, don't attempt to learn everything. Focus on learning the right things.</strong> </p>
<p>Let's break down the seven key skills that you need to focus on to build impressive applications and become an in-demand React developer.</p>
<h2 id="heading-step-1-become-confident-with-the-core-fundamentals-of-html-css-and-javascript">Step 1: Become confident with the core fundamentals of HTML, CSS, and JavaScript</h2>
<p>The first step in learning React is actually somewhat of a step backwards.</p>
<p>The building blocks of the web and every single webpage are HTML, CSS, and JavaScript. Any good React developer should know how to use them. React builds upon them to help you create apps that run on the web.</p>
<p>If you’ve built something with HTML, CSS and JavaScript already, you’re in a good place. For example, if you’ve built a complete landing page or a small website.</p>
<p>Out of the three technologies, <strong>React is most connected with JavaScript</strong>. React <em>is</em> JavaScript, with some added features. For that reason, you’ll need to have solid JavaScript skills.</p>
<h3 id="heading-what-javascript-concepts-should-you-know-for-react">What JavaScript concepts should you know for React?</h3>
<ul>
<li>Basic data structures: variables, objects, and arrays</li>
<li>Array methods and working with array data: <code>.map()</code>, <code>.filter()</code>, and <code>.reduce()</code></li>
<li>Be very familiar with functions and a little bit with classes</li>
<li>Asynchronous JavaScript: promises, making HTTP requests with Fetch API, async/await syntax can help</li>
<li>The DOM: learn to create, select and modify HTML elements as well as their attributes</li>
<li>Object and array destructuring are helpful for working with data</li>
</ul>
<p>Many developers claim that you should know "ES6/ES7/ES8/ESNext JavaScript" (in other words, the latest JavaScript features) to better learn React. Knowing more JavaScript can help, but new features can also serve as a distraction for new learners. </p>
<p>First, become confident with the JavaScript concepts I've listed above by building some small projects that require JavaScript. After that, you can take a look at some newer features of the language.</p>
<h2 id="heading-step-2-learn-react-fundamentals-and-react-hooks">Step 2: Learn React fundamentals and React hooks</h2>
<p>Once you’re confident with JavaScript, you’re ready to learn React and its core concepts. </p>
<p>These fundamentals are all React-specific and they exist to help us build applications with React, using patterns that JavaScript itself does not have.</p>
<h3 id="heading-what-react-fundamentals-do-you-need-to-know">What React fundamentals do you need to know?</h3>
<ul>
<li>How to structure JSX elements (and how it differs from plain HTML)</li>
<li>How to render (show) JSX elements and how to show or hide elements based on certain conditions</li>
<li>How to split JSX into components and how to reuse and organize those components to make our app interface.</li>
<li>How to pass data (+ JSX elements and components) to components using props and when to do so</li>
<li>How to store and update data within components using state and how to "lift state up" to other components</li>
<li>How to use event data in React and handle events from <code>onClick</code>, <code>onChange</code>, and <code>onSubmit</code> events (i.e. events from buttons, inputs, and forms)</li>
</ul>
<p>As a 7-year old library, React’s features have changed over time. A question I’m often asked is <strong>what should you learn first: the old or the new syntax?</strong> At the end of 2018, React received a large update that included features called React Hooks.</p>
<p>Hooks were a great improvement. They made React apps simpler, more powerful, and allow us to write less code. What’s important for you to know is the five core React hooks.</p>
<h3 id="heading-what-five-react-hooks-do-you-need-to-know-most-of-all">What five React Hooks do you need to know most of all?</h3>
<ul>
<li><code>useState</code>: to store and manage data within individual components</li>
<li><code>useEffect</code>: to perform actions like HTTP requests or working with a browser API</li>
<li><code>useRef</code>: to reference JSX elements</li>
<li><code>useContext</code>: to access data from React Context to share data among components more easily [rather than passing props]</li>
<li><code>useReducer</code>: to store and manage data across multiple components</li>
</ul>
<p>There are more hooks than these 5, but the others are not needed as often. So yes, you should learn the latest React features. Jump into using hooks right away. They will be the basis of every React app you make.</p>
<h2 id="heading-step-3-learn-to-fetch-data-from-both-rest-and-graphql-apis">Step 3: Learn to fetch data from both REST and GraphQL APIs</h2>
<p>A React app is the frontend of a complete application. In every application, you will likely have both a React frontend, which the user interacts with as well as a backend that our React code interacts with. The backend is where we get our data from and do other things like authenticate our users.</p>
<p>There are two ways of working with data from a backend. The standard way of getting data is from what’s called a REST API. <strong>REST APIs</strong> are the most common form of API. And the newer way is from what’s called a <strong>GraphQL API</strong>. </p>
<p>You’ll encounter both types of API in your work, so become familiar with using React to interact with both.</p>
<h2 id="heading-step-4-learn-to-style-your-react-apps-with-a-component-library-or-utility-class-library">Step 4: Learn to style your React apps with a component library or utility class library</h2>
<p>Every React app needs styling for its appearance. One choice is to use plain CSS. You can write your own styles and put them in a separate style sheet.</p>
<p>But besides CSS, many React developers use what’s known as a component library for easier styling. <strong>A component library</strong> gives us reusable components that have their own pre-made styles. The most popular component library for React is <strong>Material UI</strong>. But there are many others you can choose from.</p>
<p>Developers also use tools that provide pre-made class names called utility class libraries. Unlike a component library, <strong>a utility class library</strong> comes with pre-made classes to style your elements. </p>
<p>You can style your app by applying classnames to each element. This removes the need to write any styles yourself. The most popular utility class library is <strong>Tailwind CSS</strong>.</p>
<p>You’ll encounter both of these as a developer, so become familiar with both a component library and a utility class library.</p>
<h2 id="heading-step-5-manage-state-in-react-with-react-context">Step 5: Manage state in React with React context</h2>
<p><strong>What is state management?</strong> It’s the process of deciding where to locate data and how to work with it across our app. To manage state across your app’s components, use React Context. </p>
<p><strong>React Context</strong> is a tool that’s built into the core React library and allows us to pass data across our app's components without using props. It helps us solve the problem of prop-drilling which involves passing props (data) down to components that are deeply nested into one another. </p>
<p>With React Context, we place a value on the context we create and then access it using the <code>useContext()</code> React hook.</p>
<p><strong>What about Redux?</strong> Redux is a popular library for managing state in React apps. It is a far more complex tool than you need for most apps you’ll build. While Redux is still relied upon for very large applications, React Context will be enough for any app you make.</p>
<p>Plus you can get many of the benefits of Redux by combining React Hooks and React Context. This is a great advantage compared to learning an extra library.</p>
<h2 id="heading-step-6-learn-a-react-router-in-particular-react-router-dom">Step 6: Learn a React router. In particular, react-router-dom</h2>
<p><strong>What is a router?</strong> Any website we visit has many pages we can browse by going forward or backward in our browser’s history. To create these different pages or routes in React, we need to use what’s called a router.</p>
<p>React itself does not come with its own router, so we’re going to need to use a third party library, one called react-router-dom. </p>
<p><strong>react-router-dom</strong> is necessary for creating pages in our app, as well as navigating the user around each page. It lets us create links to different pages of our app and navigate to them or redirect them to other pages if we need.</p>
<h3 id="heading-what-features-of-react-router-dom-do-you-need-to-know">What features of react-router-dom do you need to know?</h3>
<ul>
<li>How to create app routes using the <code>&lt;Route /&gt;</code>, <code>&lt;Switch /&gt;</code>, and <code>&lt;BrowserRouter /&gt;</code> components</li>
<li>How to navigate users to different pages using the <code>&lt;Link /&gt;</code> component and programmatically using the <code>useHistory()</code> hook</li>
<li>How to create dynamic routes using the path prop (i.e. <code>&lt;Route path="/posts/:post-slug" component={Post} /&gt;</code>) and get the path's value using the <code>useParams()</code> hook</li>
<li>How to redirect users from protected content using the <code>&lt;Redirect /&gt;</code> component (see number 7)</li>
</ul>
<h2 id="heading-step-7-learn-patterns-for-authentication-in-react">Step 7: Learn patterns for authentication in React</h2>
<p>Authenticated users are people who have signed in to use our app. And we want to give those users access to different things. For that reason, authentication goes hand in hand with routing. This is because authenticated users should be able to see certain pages that unauthenticated users cannot.</p>
<h3 id="heading-what-do-you-need-to-know-about-authentication-as-a-react-developer">What do you need to know about authentication as a React developer?</h3>
<p>There is one main thing. You should learn how to show certain content to authenticated users and hide that content from unauthenticated ones.</p>
<p>In review, these are all the core skills you need to have as a React developer, capable of building complete applications and working as a hired frontend developer.</p>
<p>Beyond these 7 skills, note that there are many that can deepen your understanding as a developer. For example, learning more about browsers, HTTP, and APIs, to name a few. But if you follow all these steps, you’ll have a solid understanding of React and be able to build applications of any scale.</p>
<h2 id="heading-become-a-professional-react-developer">Become a Professional React Developer</h2>
<p>React is hard. You shouldn't have to figure it out yourself.</p>
<p>I've put everything I know about React into a single course, to help you reach your goals in record time:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><strong>Introducing: The React Bootcamp</strong></a></p>
<p><strong>It’s the one course I wish I had when I started learning React.</strong></p>
<p>Click below to try the React Bootcamp for yourself:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><img src="https://reedbarger.nyc3.digitaloceanspaces.com/reactbootcamp/react-bootcamp-cta-alt.png" alt="Click to join the React Bootcamp" width="600" height="400" loading="lazy"></a>
<em>Click to get started</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn React Context in 5 Minutes - A Beginner's Tutorial ]]>
                </title>
                <description>
                    <![CDATA[ By Bob Ziroll React's Context API has become the state management tool of choice for many, oftentimes replacing Redux altogether. In this quick 5-minute tutorial, you'll see an introduction to what Context is and how to use it! If you want a proper i... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-context-in-5-minutes/</link>
                <guid isPermaLink="false">66d45ddb8812486a37369c79</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React context ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Tutorial ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 08 Nov 2019 21:47:33 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9f7c740569d1a4ca42d5.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Bob Ziroll</p>
<p>React's Context API has become the state management tool of choice for many, oftentimes replacing Redux altogether. In this quick 5-minute tutorial, you'll see an introduction to what Context is and how to use it!</p>
<p>If you want a proper introduction to this subject, you can join the waitlist for my <a target="_blank" href="https://scrimba.com/g/greact?utm_source=freecodecamp.org&amp;utm_medium=referral&amp;utm_campaign=context_article">upcoming advanced React course</a>, or if you're still a beginner, check out my <a target="_blank" href="https://scrimba.com/g/glearnreact?utm_source=freecodecamp.org&amp;utm_medium=referral&amp;utm_campaign=context_article">free introductory course on React.</a></p>
<p>Consider this tree, in which the bottom boxes represent separate components:</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/gevur92qwoxvdjnm12dw.png" alt="Component tree" width="706" height="329" loading="lazy"></p>
<p>We can easily add state to the bottom components, but until now the only way to pass data to a component's sibling was to move state to a higher component and then pass it back down to the sibling via props.</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/u20r26dtxyr6ek6krzsb.png" alt="Passing data via props" width="716" height="337" loading="lazy"></p>
<p>If we later find out that the sibling of the component with state also needs the data, we have to lift state up again, and pass it back down:</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/wtlykrxnx8xi12h4wek4.png" alt="Passing state down through multiple levels" width="712" height="340" loading="lazy"></p>
<p>While this solution does work, problems begin if a component on a different branch needs the data:</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/g3xrvthcw24izllvb58w.png" alt="More distant component requires data" width="717" height="336" loading="lazy"></p>
<p>In this case, we need to pass state from the top level of the application through all the intermediary components to the one which needs the data at the bottom, even though the intermediary levels don't need it. This tedious and time-consuming process is known as <em>prop drilling</em>.</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/ey25z0hvmy31xiiqqwgq.png" alt="Prop drilling" width="718" height="339" loading="lazy"></p>
<p>This is where Context API comes in. It provides a way of passing data through the component tree via a Provider-Consumer pair without having to pass props down through every level. Think of it as the components playing Catch with data - the intermediary components might not even "know" that anything is happening:</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/ckfpokb2cz3ffmn8238i.png" alt="Context in action" width="714" height="350" loading="lazy"></p>
<p>To demonstrate this, we will create this funky (and super useful) day-to-night switching image.</p>
<p><a href="https://imgflip.com/gif/3evdww"><img src="https://i.imgflip.com/3evdww.gif" width="416" height="384" alt="3evdww" loading="lazy"></a></p>
<p>If you want to see the full code, be sure to check out <a target="_blank" href="https://scrimba.com/c/czkvE4sw">the Scrimba playground for this article</a>.</p>
<h1 id="heading-create-context">Create Context</h1>
<p>To begin, we create a new Context. As we want the entire app to have access to this, we go to <code>index.js</code> and wrap the app in <code>ThemeContext.Provider</code>.</p>
<p>We also pass the <code>value</code> prop to our Provider. This holds the data we want to save. For now, we just hardcode in <code>'Day'</code>.</p>
<pre><code class="lang-js"><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> ThemeContext <span class="hljs-keyword">from</span> <span class="hljs-string">"./themeContext"</span>;

<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">"./App"</span>;

ReactDOM.render(
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ThemeContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{</span>"<span class="hljs-attr">Day</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">ThemeContext.Provider</span>&gt;</span></span>,
  <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>)
);
</code></pre>
<h1 id="heading-consuming-context-with-contexttype">Consuming Context with contextType</h1>
<p>Currently, in <code>App.js</code>, we are simply returning the <code>&lt;Image /&gt;</code> component.</p>
<pre><code class="lang-js"><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> Image <span class="hljs-keyword">from</span> <span class="hljs-string">"./Image"</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">App</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  render() {
    <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">Image</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> App;
</code></pre>
<p>Our goal is to use Context to switch the classNames in <code>Image.js</code> from <code>Day</code> to <code>Night</code>, depending on which image we want to render. To do this, we add a static property to our component called <code>ContextType</code> and then use string interpolation to add it to the classNames in the <code>&lt;Image /&gt;</code> component.</p>
<p>Now, the classNames contain the string from the <code>value</code> prop. <strong>Note:</strong> I have moved <code>ThemeContext</code> into its own file to prevent a bug.</p>
<pre><code class="lang-js"><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> Button <span class="hljs-keyword">from</span> <span class="hljs-string">"./Button"</span>;
<span class="hljs-keyword">import</span> ThemeContext <span class="hljs-keyword">from</span> <span class="hljs-string">"./themeContext"</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Image</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  render() {
    <span class="hljs-keyword">const</span> theme = <span class="hljs-built_in">this</span>.context;
    <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">{</span>`${<span class="hljs-attr">theme</span>}<span class="hljs-attr">-image</span> <span class="hljs-attr">image</span>`}&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{</span>`${<span class="hljs-attr">theme</span>}<span class="hljs-attr">-ball</span> <span class="hljs-attr">ball</span>`} /&gt;</span>
        <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>
    );
  }
}

Image.contextType = ThemeContext;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Image;
</code></pre>
<h1 id="heading-contextconsumer">Context.Consumer</h1>
<p>Unfortunately, this approach only works with class-based components. If you've learned about <a target="_blank" href="https://www.freecodecamp.org/news/react-hooks-in-5-minutes/">Hooks in React</a> already, you'll know we can do just about anything with functional components these days. So for good measure, we should convert our components into functional components and then use <code>ThemeContext.Consumer</code> component to pass info through the app. </p>
<p>This is done by wrapping our elements in an instance of <code>&lt;ThemeContext.Consumer&gt;</code> and within that (where the <code>children</code> go), providing a function which returns the elements. This uses the "render prop" pattern where we provide a regular function as a child that returns some JSX to render.</p>
<pre><code class="lang-js"><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> Button <span class="hljs-keyword">from</span> <span class="hljs-string">"./Button"</span>;
<span class="hljs-keyword">import</span> ThemeContext <span class="hljs-keyword">from</span> <span class="hljs-string">"./themeContext"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Image</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-comment">// We don't need this anymore</span>
  <span class="hljs-comment">// const theme = this.context</span>

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ThemeContext.Consumer</span>&gt;</span>
      {theme =&gt; (
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{</span>`${<span class="hljs-attr">theme</span>}<span class="hljs-attr">-image</span> <span class="hljs-attr">image</span>`}&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{</span>`${<span class="hljs-attr">theme</span>}<span class="hljs-attr">-ball</span> <span class="hljs-attr">ball</span>`} /&gt;</span>
          <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">ThemeContext.Consumer</span>&gt;</span></span>
  );
}

<span class="hljs-comment">// We don't need this anymore</span>
<span class="hljs-comment">// Image.contextType = ThemeContext;</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Image;
</code></pre>
<p><strong>Note:</strong> We also need to wrap the <code>&lt;Button /&gt;</code> component in <code>&lt;ThemeContext.Consumer&gt;</code> - this allows us to add functionality to the button later.</p>
<pre><code class="lang-js"><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> ThemeContext <span class="hljs-keyword">from</span> <span class="hljs-string">"./themeContext"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Button</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ThemeContext.Consumer</span>&gt;</span>
      {context =&gt; (
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"button"</span>&gt;</span>
          Switch
          <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">role</span>=<span class="hljs-string">"img"</span> <span class="hljs-attr">aria-label</span>=<span class="hljs-string">"sun"</span>&gt;</span>
            ?
          <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">role</span>=<span class="hljs-string">"img"</span> <span class="hljs-attr">aria-label</span>=<span class="hljs-string">"moon"</span>&gt;</span>
            ?
          <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      )}
    <span class="hljs-tag">&lt;/<span class="hljs-name">ThemeContext.Consumer</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Button;
</code></pre>
<h1 id="heading-extract-context-provider">Extract Context Provider</h1>
<p>We are currently passing a hard-coded value down through the Provider, however, our goal is to switch between night and day with our button.</p>
<p>This requires moving our Provider to a separate file and putting it in its own component, in this case, called <code>ThemeContextProvider</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React, { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">const</span> { Provider, Consumer } = React.createContext();

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ThemeContextProvider</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Component</span> </span>{
  render() {
    <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{</span>"<span class="hljs-attr">Day</span>"}&gt;</span>{this.props.children}<span class="hljs-tag">&lt;/<span class="hljs-name">Provider</span>&gt;</span></span>;
  }
}

<span class="hljs-keyword">export</span> { ThemeContextProvider, Consumer <span class="hljs-keyword">as</span> ThemeContextConsumer };
</code></pre>
<p><strong>Note:</strong> the value property is now being handled in the new file ThemeContext.js, and should, therefore, be removed from index.js.</p>
<p><strong>Changing Context</strong>
To wire up the button, we first add state to <code>ThemeContextProvider</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React, { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">const</span> { Provider, Consumer } = React.createContext();

<span class="hljs-comment">// Note: You could also use hooks to provide state and convert this into a functional component.</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ThemeContextProvider</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Component</span> </span>{
  state = {
    <span class="hljs-attr">theme</span>: <span class="hljs-string">"Day"</span>
  };
  render() {
    <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{</span>"<span class="hljs-attr">Day</span>"}&gt;</span>{this.props.children}<span class="hljs-tag">&lt;/<span class="hljs-name">Provider</span>&gt;</span></span>;
  }
}

<span class="hljs-keyword">export</span> { ThemeContextProvider, Consumer <span class="hljs-keyword">as</span> ThemeContextConsumer };
</code></pre>
<p>Next, we add a method for switching between day and night:</p>
<pre><code class="lang-js">toggleTheme = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">this</span>.setState(<span class="hljs-function"><span class="hljs-params">prevState</span> =&gt;</span> {
    <span class="hljs-keyword">return</span> {
      <span class="hljs-attr">theme</span>: prevState.theme === <span class="hljs-string">"Day"</span> ? <span class="hljs-string">"Night"</span> : <span class="hljs-string">"Day"</span>
    };
  });
};
</code></pre>
<p>Now we change our <code>value</code> property to <code>this.state.theme</code> so that it returns the info from state.</p>
<pre><code class="lang-js"> render() {
    <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{this.state.theme}</span>&gt;</span>{this.props.children}<span class="hljs-tag">&lt;/<span class="hljs-name">Provider</span>&gt;</span></span>;
  }
}
</code></pre>
<p>Next, we change <code>value</code> to an object containing <code>{theme: this.state.theme, toggleTheme: this.toggleTheme}</code>, and update all the places where we use a single value to look for <code>theme</code> in an object. This means that every <code>theme</code> becomes <code>context</code> and every reference to <code>theme</code> as value becomes <code>context.theme</code>.</p>
<p>Finally, we tell the button to listen for the <code>onClick</code> event and then fire <code>context.toggleTheme</code> - this updates the Consumers which are using the state from the Provider. The code for the button looks like this:</p>
<pre><code class="lang-js"><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> { ThemeContextConsumer } <span class="hljs-keyword">from</span> <span class="hljs-string">"./themeContext"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Button</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ThemeContextConsumer</span>&gt;</span>
      {context =&gt; (
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{context.toggleTheme}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"button"</span>&gt;</span>
          Switch
          <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">role</span>=<span class="hljs-string">"img"</span> <span class="hljs-attr">aria-label</span>=<span class="hljs-string">"sun"</span>&gt;</span>
            ?
          <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">role</span>=<span class="hljs-string">"img"</span> <span class="hljs-attr">aria-label</span>=<span class="hljs-string">"moon"</span>&gt;</span>
            ?
          <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      )}
    <span class="hljs-tag">&lt;/<span class="hljs-name">ThemeContextConsumer</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Button;
</code></pre>
<p>Our button now switches the image between night and day in one click!</p>
<p><a href="https://imgflip.com/gif/3evdww"><img src="https://i.imgflip.com/3evdww.gif" width="416" height="384" alt="3evdww" loading="lazy"></a></p>
<h1 id="heading-context-caveats">Context caveats</h1>
<p>Like all good things in code, there are some caveats to using Context:</p>
<ul>
<li><p><strong>Don't use Context to avoid drilling props down just one or two layers.</strong> Context is great for managing state which is needed by large portions of an application. However, prop drilling is faster if you are just passing info down a couple of layers.</p>
</li>
<li><p><strong>Avoid using Context to save state that should be kept locally.</strong> So if you need to save a user's form inputs, for example, use local state and not Context.</p>
</li>
<li><p><strong>Always wrap the Provider around the lowest possible common parent in the tree - not the app's highest-level component.</strong> No need for overkill.</p>
</li>
<li><p><strong>Lastly, if you pass an object as your value prop, monitor performance and refactor as necessary.</strong> This probably won't be needed unless a drop in performance is noticeable.</p>
</li>
</ul>
<h1 id="heading-wrap-up">Wrap up</h1>
<p>This example is pretty simple and it would probably be easier to put state in the app and pass it down via props. However, it hopefully shows the power of having Consumers which can access data independently of the components above them in the tree.</p>
<p>To learn more about React Context and other great features of React, you can join the waitlist for my <a target="_blank" href="https://scrimba.com/g/greact?utm_source=freecodecamp.org&amp;utm_medium=referral&amp;utm_campaign=context_article">upcoming advanced React course.</a> Or if you're looking for a more beginner friendly  you can check out my <a target="_blank" href="https://scrimba.com/g/greact?utm_source=freecodecamp.org&amp;utm_medium=referral&amp;utm_campaign=context_article">free introductory course on React.</a></p>
<p>Happy coding :)</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Tips to Enhance the Performance of Your React App ]]>
                </title>
                <description>
                    <![CDATA[ By Shifa Martin ReactJS is an open-source framework that facilitates the development of UI interfaces for web and mobile applications. Developers globally use the framework to build state-of-the-art applications which subsequently generate revenues a... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/tips-to-enhance-the-performance-of-your-react-app/</link>
                <guid isPermaLink="false">66d460fa4a0edd9b48e83589</guid>
                
                    <category>
                        <![CDATA[ create-react-app ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React context ]]>
                    </category>
                
                    <category>
                        <![CDATA[ react testing library ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Reactive Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 27 Aug 2019 13:46:33 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/08/react.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Shifa Martin</p>
<p>ReactJS is an open-source framework that facilitates the development of UI interfaces for web and mobile applications. Developers globally use the framework to build state-of-the-art applications which subsequently generate revenues as well as expand the audience for businesses.  </p>
<p>However, building a great UI with React isn’t enough, You’ve got to add that extra glitter to make the app more polished, functional and remarkably better than the competition. </p>
<p>This is exactly what I’m going to help you with as I describe some key methods to increase performance in React apps.</p>
<h3 id="heading-1-making-good-use-of-identities">1. Making good use of Identities</h3>
<p>When building mobile apps with React,  it is possible to wrap functions and variables with React.useMemo. Doing so provides the ability to memoize them so they remain identical for renders in the future.  </p>
<p>When functions and variables are not memoized, any references to them might vanish from future renders. Memoizing helps in negating wasteful processes and operations in every situation where you’d leverage functions and variables.</p>
<p><em><strong>Example:</strong></em> </p>
<p>Say, we’re preparing a custom hook for a list of urls as arguments. Using the hook, we can collect them into an array of promise objects and resolve them with Promise.all. The results of this accumulation will enter the state and be passed the app component once done. The list of promises now map over the urls array from where it fetches the urls.</p>
<pre><code class="lang-react">import React from 'react'
import axios from 'axios'

export const useApp = ({ urls }) =&gt; {
  const [results, setResults] = React.useState(null)

  const promises = urls.map(axios.get)

  React.useEffect(() =&gt; {
    Promise.all(promises).then(setResults)
  }, [])

  return { results }
}

const App = () =&gt; {
  const urls = [
    'https://clinicaltables.nlm.nih.gov/api/icd10cm/v3/search?terms=a',
    'https://clinicaltables.nlm.nih.gov/api/icd10cm/v3/search?terms=b',
    'https://clinicaltables.nlm.nih.gov/api/icd10cm/v3/search?terms=c',
  ]

  useApp({ urls })

  return null
}

export default App
</code></pre>
<p>Since we want to obtain data from 3 urls here, only 3 requests are supposed to be sent out, one for each url. However,  when looking at it through the inspect element feature on Google Chrome, we find that 6 requests are sent instead of the supposed 3.<br>This happens because the urls argument did not retain its previous identity. When the app is re-rendered, it’s instantiating a new array each time, as React treats it as a different value.  </p>
<p><img src="https://lh5.googleusercontent.com/XE6rCdOL110eYARSgVTgcwiecF2qNAT96yBYn_-FbQ2_ffjdRAplLqRxu4eQh-NniyF0doEPRtsT3X0lYxeHcSu35UN0giiteCsIJTrVP9tw1mITk5-P5hH3PmdWd2ss5R0E2pb3" alt="Image" width="665" height="160" loading="lazy"></p>
<p>To fix this problem, we can use React.useMemo as previously mentioned. When using React.useMemo, the array of promise objects won’t recompute in each new render unless the array with the list of urls changes. As long as it stays the same, the identities remain.</p>
<p><strong>Here’s what happens when applying React.useMemo to this example:</strong></p>
<pre><code class="lang-react">const useApp = ({ urls }) =&gt; {
  const [results, setResults] = React.useState(null)

  const promises = urls.map((url) =&gt; axios.get(url))

  React.useEffect(() =&gt; {
    Promise.all(promises).then(setResults)
  }, [])

  return { results }
}

const App = () =&gt; {
  const urls = React.useMemo(() =&gt; {
    return [
      'https://clinicaltables.nlm.nih.gov/api/icd10cm/v3/search?terms=a',
      'https://clinicaltables.nlm.nih.gov/api/icd10cm/v3/search?terms=b',
    ]
  }, [])

  const { results } = useApp({ urls })

  return null
}
</code></pre>
<p>It will send 6 requests even now since we’ve only memoized the urls array. The promises variables are also instantiating when running the hook. So in order to send only 3  requests, we also have to memorize the promises variables as well.</p>
<pre><code class="lang-react">const promises = React.useMemo(() =&gt; {
  return urls.map((url) =&gt; axios.get(url))
}, [urls])
</code></pre>
<blockquote>
<p>After memoizing both the urls array and the promises variables, this is what we get: </p>
</blockquote>
<p><img src="https://lh4.googleusercontent.com/P-8qvsq_Nu229Eod2_FIlqLtY1_lAxkPXZfw3a9D7P25VIyGrw--kTnOuTF4rmXPsA3vxGRifwprsI_VGGDU9pFIafOAsfPKiQE3L3Zv1MHXzPH25e2g39MaCikn2AActzgJlftr" alt="Image" width="740" height="162" loading="lazy"></p>
<h3 id="heading-2-merging-props-to-children">2. Merging Props to Children</h3>
<p>At times, developers get into situations where they prefer merging a prop with children before rendering. To facilitate the same, React allows viewing the props to all react elements including others, and also allows exposing their key.</p>
<p>So developers can choose to wrap the children element with a newer one, and insert new props there or they can simply merge the props with React.</p>
<p>Say, we have an app component that uses a useModal and offers the ability to manage modals by using controls such as open, close, opened and activated. Before merging props to children, we can pass them to a VisbilityControl component which provides some additional functionality.</p>
<pre><code class="lang-react">import React from 'react'

const UserContext = React.createContext({
  user: {
    firstName: 'Kelly',
    email: 'frogLover123@gmail.com',
  },
  activated: true,
})

const VisibilityControl = ({ children, opened, close }) =&gt; {
  const ctx = React.useContext(UserContext)
  return React.cloneElement(children, {
    opened: ctx.activated ? opened : false,
    onClick: close,
  })
}

export const useModal = ({ urls } = {}) =&gt; {
  const [opened, setOpened] = React.useState(false)
  const open = () =&gt; setOpened(true)
  const close = () =&gt; setOpened(false)

  return {
    opened,
    open,
    close,
  }
}

const App = ({ children }) =&gt; {
  const modal = useModal()

  return (
    &lt;div&gt;
      &lt;button type="button" onClick={modal.opened ? modal.close : modal.open}&gt;
        {modal.opened ? 'Close' : 'Open'} the Modal
      &lt;/button&gt;
      &lt;VisibilityControl {...modal}&gt;{children}&lt;/VisibilityControl&gt;
    &lt;/div&gt;
  )
}

const Window = ({ opened }) =&gt; {
  if (!opened) return null
  return (
    &lt;div style={{ border: '1px solid teal', padding: 12 }}&gt;
      &lt;h2&gt;I am a window&lt;/h2&gt;
    &lt;/div&gt;
  )
}

export default () =&gt; (
  &lt;App&gt;
    &lt;Window /&gt;
  &lt;/App&gt;
)
</code></pre>
<p>Using Visibility control allows developers to ascertain whether the control activated is true before allowing the control opened to be used by children. In case the Visibility Control feature is used via a secret route, there’s an option to prevent unactivated users from accessing the content.  </p>
<h3 id="heading-3-making-a-larger-reducer">3. Making a larger reducer</h3>
<p>It is possible to combine to or more reducer to make a single, much larger reducer that can help boost a react app.</p>
<p>Say, you think of building a large app that provides access to a wide variety of small services. How would you go about the development of such an app? </p>
<p><strong>There are two options:</strong></p>
<ol>
<li>We can give each microservice within the app a separate part of its own from where its state and context can be managed directly.  </li>
</ol>
<ol start="2">
<li>Or we can combine all states into a single large state and manage all of them within the same environment.  </li>
</ol>
<blockquote>
<p>The first approach seems to highly tedious, so obviously, the second one is the way to go.  </p>
</blockquote>
<p><strong>Now we have three reducers to combine -</strong> </p>
<p>frogsreducer.js, authreducer.js and finally, ownersreducer.js.  </p>
<p><strong>Let's start with authReducer.js</strong></p>
<pre><code class="lang-react">const authReducer = (state, action) =&gt; {
  switch (action.type) {
    case 'set-authenticated':
      return { ...state, authenticated: action.authenticated }
    default:
      return state
  }
}

export default authReducer

ownersReducer.js
</code></pre>
<p><strong>ownersReducer.js</strong></p>
<pre><code class="lang-react">const ownersReducer = (state, action) =&gt; {
  switch (action.type) {
    case 'add-owner':
      return {
        ...state,
        profiles: [...state.profiles, action.owner],
      }
    case 'add-owner-id':
      return { ...state, ids: [...state.ids, action.id] }
    default:
      return state
  }
}

export default ownersReducer
</code></pre>
<p><strong>frogsReducer.js</strong></p>
<pre><code class="lang-react">const frogsReducer = (state, action) =&gt; {
  switch (action.type) {
    case 'add-frog':
      return {
        ...state,
        profiles: [...state.profiles, action.frog],
      }
    case 'add-frog-id':
      return { ...state, ids: [...state.ids, action.id] }
    default:
      return state
  }
}

export default frogsReducer
</code></pre>
<blockquote>
<p>Now we can put all three into the main app file and define their state:  </p>
</blockquote>
<p><strong>App.js</strong></p>
<pre><code class="lang-react">import React from 'react'
import authReducer from './authReducer'
import ownersReducer from './ownersReducer'
import frogsReducer from './frogsReducer'

const initialState = {
  auth: {
    authenticated: false,
  },
  owners: {
    profiles: [],
    ids: [],
  },
  frogs: {
    profiles: [],
    ids: [],
  },
}

function rootReducer(state, action) {
  return {
    auth: authReducer(state.auth, action),
    owners: ownersReducer(state.owners, action),
    frogs: frogsReducer(state.frogs, action),
  }
}

const useApp = () =&gt; {
  const [state, dispatch] = React.useReducer(rootReducer, initialState)

  const addFrog = (frog) =&gt; {
    dispatch({ type: 'add-frog', frog })
    dispatch({ type: 'add-frog-id', id: frog.id })
  }

  const addOwner = (owner) =&gt; {
    dispatch({ type: 'add-owner', owner })
    dispatch({ type: 'add-owner-id', id: owner.id })
  }

  React.useEffect(() =&gt; {
    console.log(state)
  }, [state])

  return {
    ...state,
    addFrog,
    addOwner,
  }
}

const App = () =&gt; {
  const { addFrog, addOwner } = useApp()

  const onAddFrog = () =&gt; {
    addFrog({
      name: 'giant_frog123',
      id: 'jakn39eaz01',
    })
  }

  const onAddOwner = () =&gt; {
    addOwner({
      name: 'bob_the_frog_lover',
      id: 'oaopskd2103z',
    })
  }

  return (
    &lt;&gt;
      &lt;div&gt;
        &lt;button type="button" onClick={onAddFrog}&gt;
          add frog
        &lt;/button&gt;
        &lt;button type="button" onClick={onAddOwner}&gt;
          add owner
        &lt;/button&gt;
      &lt;/div&gt;
    &lt;/&gt;
  )
}
export default () =&gt; &lt;App /&gt;

This is what it looks like combining all three reducers into one large reducer, along with rootReducer

function rootReducer(state, action) {
  return {
    auth: authReducer(state.auth, action),
    owners: ownersReducer(state.owners, action),
    frogs: frogsReducer(state.frogs, action),
  }
</code></pre>
<p>This is what it looks like combining all three reducers into one large reducer, along with rootReducer.</p>
<h3 id="heading-using-sentry-for-analyzing-errors">Using Sentry for Analyzing Errors</h3>
<p><img src="https://lh5.googleusercontent.com/ySh7MjcCdU2XUVc1GASq8HBz0ym9Yn3mQt8xP0fygcYWqf-UoSkOAV1gOxUSgOQ3o79FJb7R3P9iwIYngWY8MtNB6uAqHBh-UXY5gf_G-C9kN_Nuxx73iYllkPSqKKOSjDTXWvmb" alt="Image" width="1544" height="770" loading="lazy"></p>
<p>Any mobile app development project can benefit greatly from <a target="_blank" href="https://sentry.io/welcome/">Sentry.</a> It provides everything a developer needs to handle errors and exceptions when building apps with React. Sentry identifies all errors and displays them at one central location so they can be accessed and analyzed all at once.</p>
<p>Getting started with Sentry on React is easy. Just use npm install @sentry/browser and set it up. Once done, developers can log in at sentry.io and analyze all error reports of a project on a single dashboard.</p>
<p>The error reports from sentry are incredibly detailed. They provide all sorts of important information which include the user’s device information, browser, URL, stack trace, how the error was handled, source code, IP address, breadcrumbs to trace the source of error, the error function name and much more.  </p>
<h3 id="heading-5-using-axios-for-http-requests">5. Using Axios for HTTP requests</h3>
<p>Though <a target="_blank" href="https://github.com/axios/axios">Axios</a> is commonly used for HTTP requests. I felt it is important to mention this point because it's actually not common for developers to use other request libraries such as fetch for React apps.  </p>
<p>Windows.fetch provides no support for Internet Explorer 11 (most don’t really care though). But for what it's worth, Axios does work there as well and offers the ability to cancel requests in mid-flight.  </p>
<h3 id="heading-final-words">Final Words</h3>
<p>The 5 mentioned methods can greatly help speed up your React app. It helps developers, the business you’re in and of course, those who’d be using it eventually. But honestly, the success of your React App mostly depends on those who work on them. </p>
<p>As a consumer, you’d want better performance from your app, so it is what denotes success. As a developer, these methods could make your app easier to develop, and efficiency is key to being more productive. </p>
<p><strong>ValueCoders is an expert <a target="_blank" href="https://www.valuecoders.com/">IT outsourcing company</a> for software development. If you are looking for offshore React programmers or <a target="_blank" href="https://www.valuecoders.com/hire-developers/hire-android-developers">hire Android developers</a>, feel free to get in touch.</strong> </p>
<p>Also, I hope this post helps you learn new things and get a deeper insight into what goes into making the perfect react application. </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Using the React Context API  -  getting started ]]>
                </title>
                <description>
                    <![CDATA[ By Scott Spence Let's use the React Context API to change theme in an app! But first, some context! ? Ok terrible puns aside let's have a look at what the React Context API is for and what it does. There's a great one liner from the React docs... Co... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/using-the-react-context-api-getting-started-2018/</link>
                <guid isPermaLink="false">66d85236c1d58e16fbe2b41f</guid>
                
                    <category>
                        <![CDATA[ getting started ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React context ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sat, 08 Sep 2018 16:54:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/06/cover-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Scott Spence</p>
<p>Let's use the React Context API to change theme in an app!</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/zmp2k4r128poj1gsws61.gif" alt="Image" width="1512" height="865" loading="lazy"></p>
<h2 id="heading-but-first-some-context">But first, some <strong>context</strong>! ?</h2>
<p>Ok terrible puns aside let's have a look at what the React Context API is for and what it does. There's a great one liner from the <a target="_blank" href="https://reactjs.org/docs/context.html">React docs</a>...</p>
<p>Context provides a way to pass data through the component tree without having to pass props down manually at every level.</p>
<p>Or in other words, you can use the React Context API to avoid <a target="_blank" href="https://blog.kentcdodds.com/prop-drilling-bb62e02cb691">prop drilling</a> if you need more detail on the concept then please do check out the links provided.</p>
<p>I've previously gone over implementing the React Context API in <a target="_blank" href="https://blog.scottspence.me">my Gatsby blog</a> which I documented as I did it; you can see <a target="_blank" href="https://blog.scottspence.me/react-context-api-with-gatsby">how that went here</a>.</p>
<h3 id="heading-explain-the-context-api-to-me">Explain the Context API to me.</h3>
<p>A great resource on explaining the API can be found from <a target="_blank" href="https://twitter.com/leighchalliday">@leighchalliday</a> with a <a target="_blank" href="https://www.youtube.com/watch?v=yzQ_XulhQFw">great usecase</a> on the subject.</p>
<h2 id="heading-what-were-doing">What we're doing...</h2>
<p>For this post we're going to extend the example we created for <a target="_blank" href="https://blog.scottspence.me/styled-components-getting-started">styled-components getting started</a> as it has the majority of the code we'll need to get started with the React Context API.</p>
<p>We're going to extend that example to manage the theme state of the example application.</p>
<p>So in summary:</p>
<ul>
<li>Scaffold out basic CreateReact App</li>
<li>Use styled-components ? for styling</li>
<li>Add themes to switch between with the React Context API</li>
<li>Use the React Context API!</li>
</ul>
<h2 id="heading-what-well-need">What we'll need...</h2>
<p>All we'll be needing is an internet connection and a modern web browser! Because we're going to do all of this online in the awesome <a target="_blank" href="https://codesandbox.io">CodeSandbox</a>!</p>
<p>If you have a GitHub account or not, CodeSandbox will let you get started <a target="_blank" href="https://codesandbox.io/s/new">coding straight away</a>!</p>
<h3 id="heading-versions">Versions:</h3>
<p><strong>This guide is being used with the following dependency versions.</strong></p>
<ul>
<li>react: 16.4.2</li>
<li>react-dom: 16.4.2</li>
<li>react-scripts: 1.1.4</li>
<li>styled-components: 3.4.5</li>
</ul>
<hr>
<h2 id="heading-lets-start">Let's start</h2>
<p>So let's go over theming the basic create react app again, this time instead of adding state into to the component we will use the React Context API to manage the state for us. There will be people that will argue that this is a bit overkill for a theme switch but it is given as an example of <a target="_blank" href="https://reactjs.org/docs/context.html#when-to-use-context">when to use the Context API</a> in the React documentation so I will let you decide on the validity of that point. For this example, I hope it will give you a clearer picture of how to use the Context API in an application.</p>
<h3 id="heading-dependencies">Dependencies</h3>
<p><a target="_blank" href="https://codesandbox.io/s/new">Open a React CodeSandbox</a> and add <code>styled-components</code> as a dependency:</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/d49drafvtvz3ws2br9vs.gif" alt="Image" width="1512" height="865" loading="lazy"></p>
<h3 id="heading-file-structure">File structure</h3>
<p>Another area for <a target="_blank" href="https://en.wiktionary.org/wiki/bikeshedding">bikeshedding</a> is file structure, in this scenario we're adding folders for <code>components</code>, <code>contexts</code> and the <code>theme</code> please feel free to structure your files how you see fit, this is how we're going to do it for this example ❤️</p>
<p>Add the directories into the <code>src</code> folder so we can add in some components, the file structure should look something like this:</p>
<pre><code class="lang-bash">context-demo/
├─ public/
├─ src/
│  └─ components/
│  └─ contexts/
│  └─ theme/
└─ package.json
</code></pre>
<h2 id="heading-scaffold-out-a-basic-create-react-app">Scaffold out a basic Create React App</h2>
<p>Ok, so, what we're going to do is add in an <code>App.js</code> component to the <code>components</code> folder then use that in the <code>src/index.js</code> file.</p>
<p>The <code>App.js</code> component can be a <a target="_blank" href="https://reactjs.org/docs/state-and-lifecycle.html#the-data-flows-down">stateless functional component</a> as for this example as we're going to be handling state with the Context API.</p>
<p>Here you can see my sketchy typing as I create the directories and add in the <code>App.js</code> component.</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/oyxpggt00q754iv1azp0.gif" alt="Image" width="1512" height="865" loading="lazy"></p>
<p>We can then remove the <code>style.css</code> file and reference in <code>src/index.js</code> as we're going to be styling with styled-components ? and then use our <code>App.js</code> component:</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/yyne3q36jc0zca2ld89u.gif" alt="Image" width="1512" height="865" loading="lazy"></p>
<p>Ok, so the reason why I have abstracted the <code>App.js</code> component out of the <code>src/index.js</code> file is so that when we come to using the Context API we can add it to the highest level in our app, which is <code>src/index.js</code>.</p>
<h3 id="heading-what-about-the-rest">What about the rest?</h3>
<p>So this isn't really the Create React App, as we're using CodeSandbox instead, I have gone over the basic styling used in the <a target="_blank" href="https://blog.scottspence.me/styled-components-getting-started">styled-components getting started</a> post so it's time to refer to that to mimic the styles we need.</p>
<p>That means what we're going to do, rather than go into depth on the styling of each of the component parts that make up the basic Create React App appearance, we're going to re-use components, so there's going to be a bit of copy pasting involved now.</p>
<p>The Create React App boilerplate code has one file that we go over styling in the <a target="_blank" href="https://blog.scottspence.me/styled-components-getting-started">styled-components getting started</a> post which is the <code>App.js</code> file, the others are left or deleted, the basic style of <code>App.js</code> is:</p>
<p><strong><code>App.css</code></strong></p>
<pre><code class="lang-css"><span class="hljs-selector-class">.App</span> {
  <span class="hljs-attribute">text-align</span>: center;
}

<span class="hljs-selector-class">.App-logo</span> {
  <span class="hljs-attribute">animation</span>: App-logo-spin infinite <span class="hljs-number">20s</span> linear;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">80px</span>;
}

<span class="hljs-selector-class">.App-header</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#222</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">150px</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">color</span>: white;
}

<span class="hljs-selector-class">.App-title</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">1.5em</span>;
}

<span class="hljs-selector-class">.App-intro</span> {
  <span class="hljs-attribute">font-size</span>: large;
}

<span class="hljs-keyword">@keyframes</span> App-logo-spin {
  <span class="hljs-selector-tag">from</span> {
    <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">rotate</span>(<span class="hljs-number">0deg</span>);
  }
  <span class="hljs-selector-tag">to</span> {
    <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">rotate</span>(<span class="hljs-number">360deg</span>);
  }
}
</code></pre>
<h2 id="heading-use-styled-components-for-styling">Use styled components for styling</h2>
<p>Now we're going to recreate the styles from the <code>App.css</code> file with styled-components, let's list them out here and go through them:</p>
<pre><code class="lang-bash">AppWrapper
AppHeader
AppTitle
rotate360
AppLogo
<span class="hljs-comment"># We're adding our own styles for</span>
AppIntro
Underline
StyledHyperLink
Button
</code></pre>
<p><code>AppWrapper</code> is the top level wrapper which in a larger component could be used for layout with CSS Grid or Flexbox, in our case we're going to align the text center.</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/uc08zkkf4ay1hq8pkt3w.gif" alt="Image" width="1512" height="865" loading="lazy"></p>
<p>Straightforward enough, right? Now the majority of the rest of the components will use the styled-components <a target="_blank" href="https://www.styled-components.com/docs/advanced#theming"><code>ThemeProvider</code></a> which is what we're going to pass our theme to from the Context API.</p>
<h2 id="heading-add-themes-to-switch-between-with-the-react-context-api">Add themes to switch between with the React Context API</h2>
<p>Ok, we need to define some themes to pass to the <code>ThemeProvider</code>, we're going to define several theme aspects we want to change, these are going to be:</p>
<pre><code class="lang-js">primary; <span class="hljs-comment">// colour</span>
secondary; <span class="hljs-comment">// colour</span>
danger; <span class="hljs-comment">// colour</span>
fontHeader; <span class="hljs-comment">// font</span>
fontBody; <span class="hljs-comment">// font</span>
</code></pre>
<p>Create a file to contain the theme object in the <code>theme</code> directory and call it <code>globalStyle.js</code> and add in the following:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { injectGlobal } <span class="hljs-keyword">from</span> <span class="hljs-string">'styled-components'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> themes = {
  <span class="hljs-attr">theme1</span>: {
    <span class="hljs-attr">primary</span>: <span class="hljs-string">'#ff0198'</span>,
    <span class="hljs-attr">secondary</span>: <span class="hljs-string">'#01c1d6'</span>,
    <span class="hljs-attr">danger</span>: <span class="hljs-string">'#e50000'</span>,
    <span class="hljs-attr">fontHeader</span>: <span class="hljs-string">'Old Standard TT, sans, sans-serif'</span>,
    <span class="hljs-attr">fontBody</span>: <span class="hljs-string">'Nunito, sans-serif'</span>,
  },

  <span class="hljs-attr">theme2</span>: {
    <span class="hljs-attr">primary</span>: <span class="hljs-string">'#6e27c5'</span>,
    <span class="hljs-attr">secondary</span>: <span class="hljs-string">'#ffb617'</span>,
    <span class="hljs-attr">danger</span>: <span class="hljs-string">'#ff1919'</span>,
    <span class="hljs-attr">fontHeader</span>: <span class="hljs-string">'Enriqueta, sans-serif'</span>,
    <span class="hljs-attr">fontBody</span>: <span class="hljs-string">'Exo 2, sans, sans-serif'</span>,
  },

  <span class="hljs-attr">theme3</span>: {
    <span class="hljs-attr">primary</span>: <span class="hljs-string">'#f16623'</span>,
    <span class="hljs-attr">secondary</span>: <span class="hljs-string">'#2e2e86'</span>,
    <span class="hljs-attr">danger</span>: <span class="hljs-string">'#cc0000'</span>,
    <span class="hljs-attr">fontHeader</span>: <span class="hljs-string">'Kaushan Script, sans, sans-serif'</span>,
    <span class="hljs-attr">fontBody</span>: <span class="hljs-string">'Headland One, sans-serif'</span>,
  },
};

injectGlobal<span class="hljs-string">`
  @import url('
    https://fonts.googleapis.com/css?family=
    Old+Standard+TT:400,700|
    Nunito:400,700'|
    Enriqueta:400,700|
    Exo+2:400,700|
    Kaushan+Script:400,700|
    Headland+One:400,700|
  ');

  body {
    padding: 0;
    margin: 0;
  }
`</span>;
</code></pre>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/qnxbteccbaw92jbwsq9c.gif" alt="Image" width="1410" height="845" loading="lazy"></p>
<p>Ok, so nothing really happening there apart from setting up the styles for use later.</p>
<p>You will notice that <code>injectGlobal</code> is being used here, this is where we're setting the fonts for use throughout the app, <code>injectGlobal</code> <a target="_blank" href="https://stackoverflow.com/a/42899789/1138354">should be used once</a> in an app to set global styles like this.</p>
<p>Onwards! Let us now focus on getting the basic app styles into the <code>App.js</code> component. We can now start using the <code>ThemeProvider</code> in <code>App.js</code>. To do this, for now, to get some visual feedback we're going to apply one of the themes from the <code>themes</code> object in <code>globalStyle.js</code> this is so, as we are adding in components we can see the theme being applied.</p>
<p>We can do this now with the <code>AppHeader</code> which is a styled div:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> AppHeader = styled.div<span class="hljs-string">`
  height: 12rem;
  padding: 1rem;
  color: <span class="hljs-subst">${({ theme }</span>) =&gt; theme.dark};
  background-color: <span class="hljs-subst">${({ theme }</span>) =&gt; theme.primary};
`</span>;
</code></pre>
<p>You will notice here that we're beginning to use the styled-components, <code>theme</code> props but, if we paste this code in now there won't be any change until the <code>ThemeProvider</code> is passed the <code>theme</code> object so we're going to wrap <code>App.js</code> with the <code>ThemeProvider</code> component so that any component encapsulated by the <code>ThemeProvider</code> is able to receive <code>theme</code> props.</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/nuyaw29uoex6qcluf8va.gif" alt="Image" width="1410" height="845" loading="lazy"></p>
<p><code>AppTitle</code> is going to be a h1 so:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> AppTitle = styled.h1<span class="hljs-string">`
  font-family: <span class="hljs-subst">${({ theme }</span>) =&gt; theme.fontHeader};
`</span>;
</code></pre>
<p>For the spinning React logo we can use the asset used previously in the <a target="_blank" href="https://codesandbox.io/s/x26q7l9vyq">styled-components getting started example</a></p>
<p>We can add it in with the imports at the top of the <code>App.js</code> component and add it into the <code>AppLogo</code> styled component as an <code>img</code> tag:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> logo = <span class="hljs-string">`https://user-images.githubusercontent.com/
    234708/37256552-32635a02-2554-11e8-8fe3-8ab5bd969d8e.png`</span>;
</code></pre>
<p>The <code>keyframes</code> helper will need to be imported alongside the <code>ThemeProvider</code> for the animation on the react logo.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> rotate360 = keyframes<span class="hljs-string">`
  from { 
    transform: rotate(0deg); 
  }
  to { 
    transform: rotate(360deg); 
  }
`</span>;

<span class="hljs-keyword">const</span> AppLogo = styled.img<span class="hljs-string">`
  animation: <span class="hljs-subst">${rotate360}</span> infinite 5s linear;
  height: 80px;
  &amp;:hover {
    animation: <span class="hljs-subst">${rotate360}</span> infinite 1s linear;
  }
`</span>;
</code></pre>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/pxe3fb5zqvprvtjthq5b.gif" alt="Image" width="1410" height="845" loading="lazy"></p>
<h3 id="heading-shared-components">Shared components</h3>
<p>Shared components are covered in the <a target="_blank" href="https://blog.scottspence.me/styled-components-getting-started">styled-components getting started</a> guide if you need more information, for this example we're going to bring in the final couple of components as shared ones for the <code>StyledHyperLink</code> and <code>Button</code> in <code>src/Shared.js</code> add the following:</p>
<p><strong><code>src/Shared.js</code></strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> styled, { css } <span class="hljs-keyword">from</span> <span class="hljs-string">'styled-components'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> Button = styled.button<span class="hljs-string">`
  padding: 0.5rem 1rem;
  margin: 0.5rem 1rem;
  color: <span class="hljs-subst">${({ theme }</span>) =&gt; theme.primary};
  font-size: 1rem;
  box-shadow: 0 3px 5px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  border: 2px solid <span class="hljs-subst">${props =&gt; props.border}</span>;
  background-color: Transparent;
  text-transform: uppercase;
  border-radius: 4px;
  transition: all 0.1s;
  &amp;:hover {
    transform: translateY(1px);
    box-shadow: 0 2px 3px rgba(0, 0, 0, 0.15);
  }
  <span class="hljs-subst">${props =&gt;
    props.primary &amp;&amp;
    css`<span class="css">
      <span class="hljs-selector-tag">background</span>: </span><span class="hljs-subst">${({ theme }</span><span class="css">) =&gt; <span class="hljs-selector-tag">theme</span><span class="hljs-selector-class">.primary</span>};
      <span class="hljs-selector-tag">border</span>: 2<span class="hljs-selector-tag">px</span> <span class="hljs-selector-tag">solid</span> </span><span class="hljs-subst">${({ theme }</span><span class="css">) =&gt; <span class="hljs-selector-tag">theme</span><span class="hljs-selector-class">.primary</span>};
      <span class="hljs-selector-tag">color</span>: <span class="hljs-selector-tag">white</span>;
    `</span>}</span>;
  <span class="hljs-subst">${props =&gt;
    props.danger &amp;&amp;
    css`<span class="css">
      <span class="hljs-selector-tag">background</span>: </span><span class="hljs-subst">${({ theme }</span><span class="css">) =&gt; <span class="hljs-selector-tag">theme</span><span class="hljs-selector-class">.danger</span>};
      <span class="hljs-selector-tag">border</span>: 2<span class="hljs-selector-tag">px</span> <span class="hljs-selector-tag">solid</span> </span><span class="hljs-subst">${({ theme }</span><span class="css">) =&gt; <span class="hljs-selector-tag">theme</span><span class="hljs-selector-class">.danger</span>};
      <span class="hljs-selector-tag">color</span>: <span class="hljs-selector-tag">white</span>;
    `</span>}</span>;
  &amp;:hover {
    transform: translateY(2px);
    box-shadow: 0 2px 3px rgba(0, 0, 0, 0.15);
  }
`</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> StyledHyperLink = styled.a<span class="hljs-string">`
  cursor: pointer;
  &amp;:visited,
  &amp;:active {
    color: <span class="hljs-subst">${({ theme }</span>) =&gt; theme.primary};
  }
  &amp;:hover {
    color: <span class="hljs-subst">${({ theme }</span>) =&gt; theme.secondary};
  }
  color: <span class="hljs-subst">${({ theme }</span>) =&gt; theme.primary};
`</span>;
</code></pre>
<p>Then import the components like any other:</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/ipi1kdmy83ieiw6sppog.gif" alt="Image" width="1410" height="845" loading="lazy"></p>
<p>The last three components for now, <code>AppIntro</code>, <code>Underline</code> and <code>StyledHyperLink</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> AppIntro = styled.p<span class="hljs-string">`
  color: <span class="hljs-subst">${({ theme }</span>) =&gt; theme.dark};
  font-size: large;
  code {
    font-size: 1.3rem;
  }
  font-family: <span class="hljs-subst">${({ theme }</span>) =&gt; theme.fontBody};
`</span>;

<span class="hljs-keyword">const</span> Underline = styled.span<span class="hljs-string">`
  border-bottom: 4px solid <span class="hljs-subst">${({ theme }</span>) =&gt; theme.secondary};
`</span>;

<span class="hljs-keyword">const</span> StyledHyperLink = SHL.extend<span class="hljs-string">`
  text-decoration: none;
  font-family: <span class="hljs-subst">${({ theme }</span>) =&gt; theme.fontBody};
  color: <span class="hljs-subst">${({ theme }</span>) =&gt; theme.fontDark};
`</span>;
</code></pre>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/smm6hpg2w71sxm6nf3ln.gif" alt="Image" width="1410" height="845" loading="lazy"></p>
<p>Add them in under the <code>AppLogo</code> styled component and then we can add the rest of the components into the <code>App</code> function <code>return</code>, so, ready for another copy pasta? Here:</p>
<pre><code class="lang-js">&lt;AppIntro&gt;
  Bootstrapped <span class="hljs-keyword">with</span>{<span class="hljs-string">' '</span>}
  &lt;Underline&gt;
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">code</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">StyledHyperLink</span>
        <span class="hljs-attr">href</span>=<span class="hljs-string">{</span>`<span class="hljs-attr">https:</span>//<span class="hljs-attr">github.com</span>/<span class="hljs-attr">facebook</span>/<span class="hljs-attr">create-react-app</span>`}
        <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>
        <span class="hljs-attr">rel</span>=<span class="hljs-string">"noopener"</span>
      &gt;</span>
        create-react-app
      <span class="hljs-tag">&lt;/<span class="hljs-name">StyledHyperLink</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">code</span>&gt;</span></span>
  &lt;/Underline&gt;.
&lt;/AppIntro&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">AppIntro</span>&gt;</span>
  Components styled with{' '}
  <span class="hljs-tag">&lt;<span class="hljs-name">Underline</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">code</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">StyledHyperLink</span>
        <span class="hljs-attr">href</span>=<span class="hljs-string">{</span>`<span class="hljs-attr">https:</span>//<span class="hljs-attr">www.styled-components.com</span>`}
        <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>
        <span class="hljs-attr">rel</span>=<span class="hljs-string">"noopener"</span>
      &gt;</span>
        styled-components
      <span class="hljs-tag">&lt;/<span class="hljs-name">StyledHyperLink</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">code</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">Underline</span>&gt;</span>{' '}
  <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">role</span>=<span class="hljs-string">"img"</span> <span class="hljs-attr">aria-label</span>=<span class="hljs-string">"nail polish"</span>&gt;</span>
    ?
  <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">AppIntro</span>&gt;</span></span>
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">AppIntro</span>&gt;</span>
  Fonts picked with{' '}
  <span class="hljs-tag">&lt;<span class="hljs-name">Underline</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">code</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">StyledHyperLink</span>
        <span class="hljs-attr">href</span>=<span class="hljs-string">{</span>`<span class="hljs-attr">https:</span>//<span class="hljs-attr">fontjoy.com</span>/`}
        <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>
        <span class="hljs-attr">rel</span>=<span class="hljs-string">"noopener"</span>
      &gt;</span>
        fontjoy.com
      <span class="hljs-tag">&lt;/<span class="hljs-name">StyledHyperLink</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">code</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">Underline</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">AppIntro</span>&gt;</span></span>
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Button</span>&gt;</span>Normal Button<span class="hljs-tag">&lt;/<span class="hljs-name">Button</span>&gt;</span></span>
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Button</span> <span class="hljs-attr">primary</span>&gt;</span>Primary Button<span class="hljs-tag">&lt;/<span class="hljs-name">Button</span>&gt;</span></span>
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Button</span> <span class="hljs-attr">danger</span>&gt;</span>Danger Button<span class="hljs-tag">&lt;/<span class="hljs-name">Button</span>&gt;</span></span>
</code></pre>
<p>Sorry for the code wall! Right paste that in under the closing <code>&lt;/AppHeader&gt;</code> tag and we should have the base of what we're going to theme!</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/zfcnihvmyvb9my5dn11x.gif" alt="Image" width="1410" height="845" loading="lazy"></p>
<p>Ok? How's it looking?</p>
<p>Now we have a basic React app that uses styled-components!</p>
<h2 id="heading-use-the-react-context-api">Use the React Context API</h2>
<p>Now for the main event! Here we're going to cover:</p>
<p>Making the theme context.</p>
<p>Using the context API with a component.</p>
<p>Consuming the Context API in multiple components.</p>
<p>So, passing state needlessly through components is what we can use the Context API to avoid. If we take a look at the <a target="_blank" href="https://codesandbox.io/s/x26q7l9vyq">styled-components getting started example</a> we can see the state being managed in the <code>App.js</code> component and the <code>handleThemeChange</code> function has to be passed to the <code>ThemeSelect</code> component much the same way as any props would need to be passed down. That is a simplified example but it's quite easy to imagine if that component lived on a footer component or a menu item there would be several other components that would need to have the state passed through them that would not actually need that state or props. Make sense?</p>
<p><strong>example</strong></p>
<pre><code class="lang-js">&lt;App&gt;               {<span class="hljs-comment">/* state begins here */</span>}
  &lt;Header&gt;          {<span class="hljs-comment">/* through here */</span>}
    &lt;Navigation&gt;    {<span class="hljs-comment">/* and here */</span>}
      &lt;ThemeSelect&gt; {<span class="hljs-comment">/* to be used here */</span>}
    &lt;/Navigation&gt;
  &lt;/Header&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Footer</span>/&gt;</span></span>
&lt;/App&gt;
</code></pre>
<h3 id="heading-add-the-site-theme-context">Add the site theme context</h3>
<p>In our <code>src/contexts/</code> directory we're going to make our <code>SiteThemeContext.js</code>, import React and define and export our context:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> SiteThemeContext = React.createContext();
</code></pre>
<h3 id="heading-so-what-is-a-context">So what is a context?</h3>
<p>A context is made up of two things, a provider and a consumer, you have a single provider which will sit up as high as possible in the component tree so that multiple consumers can get the state and props from the provider.</p>
<p>Hopefully you recall the point at which we abstracted the <code>function App</code> component out of the <code>src/index.js</code> file, this is so we could add in the context provider at the highest level of the app, in the <code>src/index.js</code> file. This means that any consumer within the app, no matter how deep into the component tree it is, it can get the state and props from that top level.</p>
<p>Now to create a provider, the provider is a regular React component, so:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> SiteThemeContext = React.createContext()

<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SiteThemeProvider</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">SiteThemeContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{}</span>&gt;</span>
        {this.props.children}
      <span class="hljs-tag">&lt;/<span class="hljs-name">SiteThemeContext.Provider</span>&gt;</span></span>
    )
  }
}
</code></pre>
<p>What is being returned by <code>&lt;SiteThemeProvider&gt;</code> is the <code>&lt;SiteThemeContext.Provider&gt;</code> and the children of that component, the one prop you have to provide the the provider is a <code>value</code> prop. This is the variable that the consumer has access to. The consumer being <code>&lt;SiteThemeContext.Consumer&gt;</code> (more on this shortly).</p>
<p>So what we can do now is have what is passed into <code>value</code> be an object <code>value={{}}</code> so it can store multiple properties of the state and the functions that are defined in <code>SiteThemeContext</code>.</p>
<p>The state for the context needs to be the <code>theme</code> so we need to import the theme from <code>src/theme/globalStyle</code> and add that to the state, we're going to default the theme (and state) to <code>theme1</code> and add a copy of that into the <code>value</code> prop by spreading into state <code>...❤️</code>, it should look like this:</p>
<pre><code class="lang-js"><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> PropTypes <span class="hljs-keyword">from</span> <span class="hljs-string">'prop-types'</span>;

<span class="hljs-keyword">import</span> { themes } <span class="hljs-keyword">from</span> <span class="hljs-string">'../theme/globalStyle'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> SiteThemeContext = React.createContext();

<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SiteThemeProvider</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  state = {
    <span class="hljs-attr">theme</span>: themes[<span class="hljs-string">'theme1'</span>],
  };

  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">SiteThemeContext.Provider</span>
        <span class="hljs-attr">value</span>=<span class="hljs-string">{{</span>
          <span class="hljs-attr">...this.state</span>,
        }}&gt;</span>
        {this.props.children}
      <span class="hljs-tag">&lt;/<span class="hljs-name">SiteThemeContext.Provider</span>&gt;</span></span>
    );
  }
}
</code></pre>
<p>Ok, it's been a while since I've added a gif, time for another one!</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/n2qbxs7cbf7w5opqcri2.gif" alt="Image" width="1410" height="845" loading="lazy"></p>
<p>And bring in the <code>themes</code> and add state:</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/y6n32p1gshah5ex747mu.gif" alt="Image" width="1410" height="845" loading="lazy"></p>
<p>Now we can add in a function to the provider to change the theme state based on what has been selected via the <code>handleThemeChange</code> event value:</p>
<pre><code class="lang-js">handleThemeChange = <span class="hljs-function"><span class="hljs-params">e</span> =&gt;</span> {
  <span class="hljs-keyword">const</span> key = e.target.value;
  <span class="hljs-keyword">const</span> theme = themes[key];
  <span class="hljs-built_in">this</span>.setState({ theme });
};
</code></pre>
<p>This can then be consumed by any provider that wants to use it, we're going to need to add it into the <code>value</code> prop, like this:</p>
<pre><code class="lang-js"><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> PropTypes <span class="hljs-keyword">from</span> <span class="hljs-string">'prop-types'</span>;

<span class="hljs-keyword">import</span> { themes } <span class="hljs-keyword">from</span> <span class="hljs-string">'../theme/globalStyle'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> SiteThemeContext = React.createContext();

<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SiteThemeProvider</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  state = {
    <span class="hljs-attr">theme</span>: themes[<span class="hljs-string">'theme1'</span>],
  };

  handleThemeChange = <span class="hljs-function"><span class="hljs-params">e</span> =&gt;</span> {
    <span class="hljs-keyword">const</span> key = e.target.value;
    <span class="hljs-keyword">const</span> theme = themes[key];
    <span class="hljs-built_in">this</span>.setState({ theme });
  };

  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">SiteThemeContext.Provider</span>
        <span class="hljs-attr">value</span>=<span class="hljs-string">{{</span>
          <span class="hljs-attr">...this.state</span>,
          <span class="hljs-attr">handleThemeChange:</span> <span class="hljs-attr">this.handleThemeChange</span>,
        }}&gt;</span>
        {this.props.children}
      <span class="hljs-tag">&lt;/<span class="hljs-name">SiteThemeContext.Provider</span>&gt;</span></span>
    );
  }
}
</code></pre>
<p>Ok, that is the site theme context component covered, pretty straight forward, right?</p>
<p>What I should mention is that the <code>e</code> in the <code>handleThemeChange</code> function is going to be the event from the theme select box that we're about to make.</p>
<p>Let's go through adding in the function and adding that to the state:</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/3bh3bwi4ekb24uowvm65.gif" alt="Image" width="1410" height="845" loading="lazy"></p>
<p>And now we can add the theme provider to <code>src/index.js</code> so anything lower in the dependency tree can access it via a consumer.</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/p8nibx8ecfildi92jscm.gif" alt="Image" width="1512" height="865" loading="lazy"></p>
<h3 id="heading-add-the-theme-select">Add the theme select</h3>
<p>Now we want a want to call the <code>handleThemeChange</code> function that is part of the <code>SiteThemeProvider</code> via the <code>SiteThemeContext</code>! I'm sure this all making perfect sense right now (?) so let's get right in there and define the component that we're going to use to consume the <code>SiteThemeContext.Provider</code> with a <code>ThemeSelect</code> component!</p>
<p>In the <code>src/components</code> directory add a new <code>ThemeSelect.js</code> component, this is where we are going to consume the site theme context with a consumer.</p>
<p>The child of a consumer isn't a component it's a function, so what we're going to need to do is have the theme select inside the return of that function.</p>
<p>Let's first set up the styled-components that will make up the select, which is a select box, some options and a wrapper.</p>
<p>First we'll do it without the consumer then we'll add it in.</p>
<p><strong><code>ThemeSelect.js</code></strong></p>
<pre><code class="lang-js"><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> styled <span class="hljs-keyword">from</span> <span class="hljs-string">'styled-components'</span>;

<span class="hljs-keyword">import</span> { themes } <span class="hljs-keyword">from</span> <span class="hljs-string">'../theme/globalStyle'</span>;

<span class="hljs-keyword">const</span> SelectWrapper = styled.div<span class="hljs-string">`
  margin: 0rem 0.5rem 0rem 0.25rem;
  padding: 0rem 0.5rem 0rem 0.25rem;
`</span>;

<span class="hljs-keyword">const</span> Select = styled.select<span class="hljs-string">`
  margin: 1.5rem 0.5rem;
  padding: 0.25rem 0.5rem;
  font-family: <span class="hljs-subst">${({ theme }</span>) =&gt; theme.fontBody};
  border: 2px solid <span class="hljs-subst">${({ theme }</span>) =&gt; theme.secondary};
  box-shadow: 0px 0px 0px 1px rgba(0, 0, 0, 0.1);
  background: <span class="hljs-subst">${({ theme }</span>) =&gt; theme.foreground};
  border-radius: 4px;
`</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> SelectOpt = styled.option<span class="hljs-string">`
  font-family: <span class="hljs-subst">${({ theme }</span>) =&gt; theme.fontBody};
`</span>;

<span class="hljs-keyword">const</span> ThemeSelect = <span class="hljs-function"><span class="hljs-params">props</span> =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">SelectWrapper</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Select</span>&gt;</span>
        {Object.keys(themes).map((theme, index) =&gt; {
          return (
            <span class="hljs-tag">&lt;<span class="hljs-name">SelectOpt</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{index}</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{theme}</span>&gt;</span>
              Theme {index + 1}
            <span class="hljs-tag">&lt;/<span class="hljs-name">SelectOpt</span>&gt;</span>
          );
        })}
      <span class="hljs-tag">&lt;/<span class="hljs-name">Select</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">SelectWrapper</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ThemeSelect;
</code></pre>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/43e15llsi8uhlmi1z1ut.gif" alt="Image" width="1512" height="865" loading="lazy"></p>
<p>So from this we can list the this themes available to us in the <code>themes</code> object. But that's it, the function to handle the theme change lives on the <code>SiteThemeProvider</code>.</p>
<p>Back to the <code>SiteThemeContext.Consumer</code> as I mentioned earlier the child of a consumer is a function <code>() =&gt; ()</code> the first section is the <code>value</code> from the provider (<code>&lt;SiteThemeContext.Provider&gt;</code>) so let's take a quick look at what we've previously defined in the provider:</p>
<pre><code class="lang-js">value={{
  ...this.state,
  <span class="hljs-attr">handleThemeChange</span>: <span class="hljs-built_in">this</span>.handleThemeChange
}}
</code></pre>
<p>Available from <code>SiteThemeContext.Provider</code> is the state and a function so any of those items we can extract and pass to the provider, or to put it another way the consumer can access those values.</p>
<p>Here we can use destructuring to pull the <code>handleThemeChange</code> function we need to change the theme.</p>
<pre><code class="lang-js"><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> { SiteThemeContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'../contexts/SiteThemeContext'</span>

<span class="hljs-keyword">const</span> ThemeSelect = <span class="hljs-function"><span class="hljs-params">props</span> =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">SiteThemeContext.Consumer</span>&gt;</span>
      {({ handleThemeChange }) =&gt; ()}
    <span class="hljs-tag">&lt;/<span class="hljs-name">SiteThemeContext.Consumer</span>&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ThemeSelect
</code></pre>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/1qq4hc2zqa50t0t2vi5v.gif" alt="Image" width="1512" height="865" loading="lazy"></p>
<p>Currently this isn't going to change the theme because we have that hardcoded into the styled-components <code>ThemeProvider</code>, what we want to do is use a consumer for the currently selected theme in the <code>SiteThemeContext</code>.</p>
<p>Before that we'll also need to add in the <code>onChange</code> event we want to use to pass the event (<code>e</code>) to the <code>handleThemeChange</code> function on <code>SiteThemeContext</code>.</p>
<p>Then in the <code>App</code> component we can import our <code>&lt;SiteThemeContext.Consumer&gt;</code> to consume the <code>theme</code> on the <code>SiteThemeContext</code> state and pass that to the styled-components <code>ThemeProvider</code>.</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/jn5u8bzuvufpa56c9ta7.gif" alt="Image" width="1512" height="865" loading="lazy"></p>
<h3 id="heading-want-to-know-more">Want to know more?</h3>
<p>As mentioned at the start of this article a great resource is <a target="_blank" href="https://twitter.com/leighchalliday">@leighchalliday</a> and <a target="_blank" href="https://www.youtube.com/channel/UCWPY8W-FAZ2HdDiJp2RC_sQ">his YouTube channel</a> where you can find his <a target="_blank" href="https://www.youtube.com/watch?v=yzQ_XulhQFw">great usecase</a> for the React Context API.</p>
<p>There's also the <a target="_blank" href="https://spectrum.chat/react">React community on spectrum</a> and <a target="_blank" href="https://spectrum.chat/styled-components">styled-components on spectrum</a>.</p>
<p><a target="_blank" href="https://codesandbox.io/s/5vl16n5oxp">Example code</a> of the walkthrough is available on <a target="_blank" href="https://codesandbox.io">CodeSandbox</a>.</p>
<h3 id="heading-thanks-for-reading">Thanks for reading</h3>
<p>If there is anything I have missed, or if there is a better way to do something then please let me know.</p>
<p>Follow me on <a target="_blank" href="https://twitter.com/spences10">Twitter</a> or <a target="_blank" href="https://github.com/spences10/ama">Ask Me Anything</a> on GitHub.</p>
<blockquote>
<p><strong>You can read other articles like this on <a target="_blank" href="https://thelocalhost.blog/">my blog</a>.</strong></p>
</blockquote>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
