<?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 hooks - 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 hooks - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 23 Jun 2026 22:45:18 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/react-hooks/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ What's the Difference Between the useMemo and useCallback Hooks? ]]>
                </title>
                <description>
                    <![CDATA[ React provides various hooks that make it easier to manage application state and other React features in functional components. Hooks provide class component features to functional components, and they don't need a lot of code compared to class compo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/difference-between-usememo-and-usecallback-hooks/</link>
                <guid isPermaLink="false">66d8514dec0a9800d5b8e6ea</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ react hooks ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kunal Nalawade ]]>
                </dc:creator>
                <pubDate>Mon, 15 Jul 2024 19:14:59 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/07/photo-1619410283995-43d9134e7656.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>React provides various hooks that make it easier to manage application state and other React features in functional components. Hooks provide class component features to functional components, and they don't need a lot of code compared to class components.</p>
<p>Hooks also make your life easier by providing some convenient features. Among these hooks, we have <code>useMemo</code> and <code>useCallback</code> that help improve your website's performance.</p>
<p>In today's tutorial, we are going to discuss both the <code>useMemo</code> and <code>useCallback</code> hooks. You'll learn the difference between them and when to use each hook.</p>
<h2 id="heading-the-usememo-hook">The <code>useMemo</code> Hook</h2>
<p>The <code>useMemo</code> hook <em>memoizes</em> the return value of an expensive calculation between renders. Memoizing means storing the value as a cached value so that the value need not be calculated again (unless it's required).</p>
<p><code>useMemo</code> is a hook used for optimising the performance of your renders. Normally, when you declare a variable inside a component, it gets re-created on every render. If it stores the return value of a function, then the function gets called every time your component renders.</p>
<p>Normally, this wouldn't be a problem. But, what if the function is expensive? What if it takes a longer time to execute? Take the following example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculate</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> result = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">1000000000</span>; i++) {
    result += i;
  }
  <span class="hljs-keyword">return</span> result;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App1</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);

  <span class="hljs-keyword">const</span> value = calculate();

  <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">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setCount(count + 1)}&gt;Increment Count<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Count: {count}<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>
  );
}
</code></pre>
<p>When you click on 'Increment Count', it takes a few seconds to update the count state. This is because the <code>calculate</code> function runs every time a component re-renders after state change.</p>
<p>Now, imagine if there were multiple state variables in the component, each serving its own purpose. Each state update would cause a re-render and execute this expensive function.</p>
<p>These state variables could be completely unrelated to the expensive calculation performed, which would cause unnecessary delays. This would affect the performance of your website and could lead to a terrible user experience.</p>
<p><code>useMemo</code> can help you tackle this issue. Let's first understand its syntax:</p>
<pre><code class="lang-python">const value = useMemo(expensiveFunction, [...dependencyArray])
</code></pre>
<p>The <code>useMemo</code> hook should be declared at the top level of your component. It takes the following arguments:</p>
<ul>
<li><p><code>expensiveFunction</code> contains the expensive calculation you want to perform. If you have declared the function outside, pass the function reference only, without the brackets. You can also pass arrow functions directly.</p>
</li>
<li><p><code>dependencyArray</code> contains list of dependencies for the hook. The expensive function will be called only when one of these dependencies is updated. You can pass state variables or props that are dependent on this calculation. Any other state updates will not trigger the function.</p>
</li>
</ul>
<p>On the first render, <code>useMemo</code> returns the result of <code>expensiveFunction</code> and caches the result. During the subsequent renders, it will return the cached value if no dependencies have changed. If they change, then it will call the function again.</p>
<p>Let's use this in our case:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> [dependentCount, setDependentCount] = useState(<span class="hljs-number">10</span>);

<span class="hljs-keyword">const</span> value = useMemo(calculate, [dependentCount]);

<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">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setDependentCount(dependentCount + 1)}&gt;
      Increment Dependent Count
    <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Dependent Count: {dependentCount}<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>
);
</code></pre>
<p>We have created another state <code>dependentCount</code> that we assume is dependent on the expensive calculation. When this state updates and renders the component, the <code>calculate</code> function will run.</p>
<p>But if any other state changes, then <code>useMemo</code> will return the cached value instead of running the function again.</p>
<p>Let's test this by adding a <code>console.log</code> inside the function:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/image-28.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Output with useMemo</em></p>
<p>Now, when you click "Increment Count", the rendering is faster, since the <code>calculate</code> function is not getting called on every render. This is the same during every other state update not listed in the useMemo dependency array.</p>
<p>But when you click on "Increment dependent Count", it takes time to render the updated value. This is because <code>dependentCount</code> is a dependency of <code>useMemo</code> and changing it calls the expensive function, so the component takes time to re-render.</p>
<p>In this way, with <code>useMemo</code>, you can control the execution of an expensive function by calling it only for state updates that actually need the value returned. This can drastically improve your app's performance.</p>
<h3 id="heading-when-to-use-usememo">When to use <code>useMemo</code>:</h3>
<ul>
<li><p>When you have a state dependent on an expensive calculation, but you don't want to run the calculation on every render.</p>
</li>
<li><p>When you declare an array or object inside a component, its reference changes on every render, even though the value remains the same. Wrapping the values inside <code>useMemo</code> maintains referential equality and prevents unnecessary re-renders. This is essential when there's a <code>useEffect</code> dependent on the array or object.</p>
</li>
<li><p>When you are rendering lists using <code>Array.map</code> that do not need to change unless a certain state value changes.</p>
</li>
</ul>
<h2 id="heading-the-usecallback-hook">The <code>useCallback</code> Hook</h2>
<p>Similar to <code>useMemo</code>, you can also use this hook to optimise performance. The <code>useCallback</code> hook memoizes a callback function and returns it.</p>
<p>Note that the <code>useCallback</code> hook memoizes the function itself, not its return value. <code>useMemo</code> caches the functions return value so that the function need not execute again. <code>useCallback</code> caches the function definition or the function reference.</p>
<p>A function declared inside a component gets re-created on every component render, similar to a variable. The difference is, it gets rendered with a different reference every time. So, a <code>useEffect</code> dependent on this function will execute again on each render. A similar thing happens with child components.</p>
<p>Let's take an example:</p>
<pre><code class="lang-python">const App = () =&gt; {
  const [count, setCount] = useState(<span class="hljs-number">0</span>);
  const [value, setValue] = useState(<span class="hljs-string">""</span>);

  const handleClick = () =&gt; {
    setValue(<span class="hljs-string">"Kunal"</span>);
  };
  <span class="hljs-keyword">return</span> (
    &lt;div className=<span class="hljs-string">"App"</span>&gt;
      &lt;button onClick={() =&gt; setCount(count + <span class="hljs-number">1</span>)}&gt;Increment Count&lt;/button&gt;
      &lt;p&gt;Count: {count}&lt;/p&gt;
      &lt;p&gt;Value: {value}&lt;/p&gt;
      &lt;SlowComponent handleClick={handleClick} /&gt;
    &lt;/div&gt;
  );
};

const SlowComponent = React.memo(({ handleClick, value }) =&gt; {

  // Intentially making the component slow
  <span class="hljs-keyword">for</span> (let i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">1000000000</span>; i++) {}

  <span class="hljs-keyword">return</span> (
    &lt;div&gt;
      &lt;h1&gt;Slow Component&lt;/h1&gt;
      &lt;button onClick={handleClick}&gt;Click Me&lt;/button&gt;

    &lt;/div&gt;
  );
});
</code></pre>
<p>Here, we have a <code>SlowComponent</code> as the child of the <code>App</code> component. When a parent component renders, all of its child components render, regardless of whether anything has changed inside them.</p>
<p>To avoid unnecessary renders of the child components, we generally use the <code>React.memo</code> function. This basically caches the component and only re-renders it if its props have changed.</p>
<p>Now, when you click on 'Increment Count', it still takes a long time to render, because <code>SlowComponent</code> re-renders on state change. But why is that? We're not changing any of its props.</p>
<p>On the surface, we may not appear to change the value of <code>handleClick</code> prop. But, since functions are re-created with a different reference, on every render of the App component, its child (that is <code>SlowComponent</code>) renders.</p>
<p>To maintain referential equality, we wrap this function's definition inside a <code>useCallback</code>.</p>
<p>Let's understand its syntax:</p>
<pre><code class="lang-python">const cachedFn = useCallback(fn, [...dependencyArray])
</code></pre>
<p><code>useCallback</code> takes the following arguments:</p>
<ul>
<li><p><code>fn</code> is the function you want to cache. It is the function definition that you want to create, and can take any arguments and return any value.</p>
</li>
<li><p><code>dependencyArray</code> is a list of dependencies, changes to which trigger re-creation of the function. You can pass state values or props that are dependent on this function.</p>
</li>
</ul>
<p>On the first render, React creates the function (does not call it) and caches it. On the subsequent renders, the cached function is returned to you. Remember, this hook returns and caches the <em>function</em> and not its return value.</p>
<p>Let's use this hook in our example:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> { useCallback } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

const App = () =&gt; {

  // ...

  const handleClick = useCallback(() =&gt; {
    setValue(<span class="hljs-string">"Kunal"</span>);
  }, [value, setValue]);

  // ...
};
</code></pre>
<p>Here, we have wrapped the function inside a <code>useCallback</code> and passed two dependencies that are involved with this function.</p>
<p>Now, when you click on 'Increment Count', the rendering is much faster. This is because the <code>handleClick</code> reference is cached between renders and hence, <code>SlowComponent</code> does not re-render.</p>
<p>But when you click on the button inside <code>SlowComponent</code> it will re-render. This is because when the <code>value</code> state changes, the <code>handleClick</code> method is created again and so the props of the slow component have changed.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/07/image-33.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Value takes time to render</em></p>
<p>You can add many more states to the <code>App</code> component and update them without inhibiting performance as long as you don't update <code>value</code>'s state.</p>
<h3 id="heading-when-to-use-usecallback">When to use <code>useCallback</code></h3>
<ul>
<li><p>When you have event handlers defined for an element inside your component, wrap them inside a <code>useCallback</code> to avoid unnecessary re-creations of event handlers.</p>
</li>
<li><p>When you call a function inside a <code>useEffect</code>, you usually pass the function as a dependency. To avoid using <code>useEffect</code> unnecessarily on every render, wrap the function definition inside a <code>useCallback</code>.</p>
</li>
<li><p>If you are writing a custom hook, and it returns a function, it is recommended to wrap it inside a <code>useCallback</code>. So, there's no need for the users to worry about optimizing the hook – rather, they can focus on their own code.</p>
</li>
</ul>
<h2 id="heading-differences-between-usememo-and-usecallback">Differences Between <code>useMemo</code> and <code>useCallback</code></h2>
<p>Let's summarize the differences between the two hooks:</p>
<ul>
<li><p><code>useMemo</code> caches the return value of a function. <code>useCallback</code> caches the function definition itself.</p>
</li>
<li><p><code>useMemo</code> is used when you have an expensive calculation you want to avoid on every render.</p>
</li>
<li><p><code>useCallback</code> is used to cache a function to avoid re-creating it on every re-render.</p>
</li>
<li><p><code>useMemo</code> makes sure that an expensive function should only be called for state values dependent on it.</p>
</li>
<li><p><code>useCallback</code> creates stable functions that maintain the same reference between renders. This avoids unnecessary rendering of child components.</p>
</li>
</ul>
<p>And here are a few more things to remember. Use these hooks only if you want to memoize expensive calculations or prevent unnecessary re-renders. Do not use <code>useMemo</code> and <code>useCallback</code> everywhere.</p>
<p>For regular functions, these hooks don't make much difference. Overusing them will make your code unreadable. Instead, you can figure out other ways to improve app performance.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p><code>useMemo</code> and <code>useCallback</code> are useful hooks in React that can help you optimize performance of your web app. It is important to understand the difference between the two and their usages.</p>
<p>In this article, we have discussed how both hooks work. <code>useMemo</code> caches the result of an expensive calculation, while <code>useCallback</code> caches the function reference. We also listed down scenarios when you should use each hook. Together, both these hooks can make your website faster.</p>
<p>I hope this article helps clear up any confusion. If you have further questions or comments regarding the post, reach out to me on Twitter. I would love to hear suggestions. Till next time, goodbye!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use the useReducer Hook in React ]]>
                </title>
                <description>
                    <![CDATA[ In this article, we'll take a deep look at the useReducer hook in React. It can look confusing, especially if you are coming across the hook for the first time. This article breaks down the useReducer hook concept into understandable bits with both c... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-usereducer-hook/</link>
                <guid isPermaLink="false">66ba292e99186a3f75f2230b</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ react hooks ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Timothy Olanrewaju ]]>
                </dc:creator>
                <pubDate>Fri, 03 May 2024 17:48:03 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/05/Introduction-to-useReducer-Hook.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this article, we'll take a deep look at the <code>useReducer</code> hook in React. It can look confusing, especially if you are coming across the hook for the first time. This article breaks down the <code>useReducer</code> hook concept into understandable bits with both code and real-world examples to enable you grasp its functionality.</p>
<p>If you are having a tough time understanding what the <code>useReducer</code> is and how it works, this article is for you. However, a good knowledge of how states works is essential to understand what will be covered in this piece. You can read about React states here: <a target="_blank" href="https://www.freecodecamp.org/news/react-state-management/#:~:text=State%20management%20is%20a%20crucial,placed%20in%20your%20applications">State Management In React</a>. You can then join us on the ride to the <code>useReducer</code> land when you are done. If you are already familiar with states, lets go!</p>
<p>Before we go any further, it is important to note that the <code>useState</code> and <code>useReducer</code> hooks are similar in some ways.</p>
<h2 id="heading-how-does-usereducer-compare-to-the-usestate-hook">How Does <code>useReducer</code> Compare to the <code>useState</code> Hook?</h2>
<ul>
<li>They both involve a current state value, and have a function that triggers a state update and an initial state value passed as an argument.</li>
<li>The <code>useReducer</code> is an alternative to the <code>useState</code> hook for managing state in functional components. The <code>useReducer</code> hook is better suited for managing complex state logic while <code>useState</code> is best for simple state changes.</li>
</ul>
<p>When the state logic becomes too complicated or when you need to handle state changes in a more predictable and manageable way, the <code>useReducer</code> hook is your best bet.</p>
<h2 id="heading-what-is-usereducer">What is <code>useReducer</code>?</h2>
<p>A <code>useReducer</code> is a hook in React that allows you add a <code>reducer</code> to your component. It takes in the reducer function and an <code>initialState</code> as arguments. The <code>useReducer</code> also returns an array of the current <code>state</code> and a <code>dispatch</code> function.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> [state, dispatch] = useReducer(reducer, initialState);
</code></pre>
<p>Let's familiarize ourselves with what the parameters mean:</p>
<ul>
<li><code>state</code>: represents the current value and is set to the <code>initialState</code> value during the initial render.</li>
<li><code>dispatch</code>: is a function that updates the state value and always triggers a re-render, just like the updater function in <code>useState</code>.</li>
<li><code>reducer</code>: is a function that houses all the logic of how the state gets updated. It takes state and action as arguments and returns the next state.</li>
<li><code>initialState</code>: houses the initial value and can be of any type.</li>
</ul>
<h2 id="heading-deep-dive-into-usereducer">Deep dive into <code>useReducer</code></h2>
<p>Having seen the parts that makes up a useReducer hook, it is time to take a closer look into how it operates.</p>
<p>To use useReducer in your React app, call it at the top level of your component.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useReducer } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
</code></pre>
<p>We can now use the useReducer hook in our 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"></span>) </span>{
  <span class="hljs-keyword">const</span> [state, dispatch] = useReducer(reducer, initialState);

  <span class="hljs-keyword">return</span>(
  )
 }
</code></pre>
<p>To see our <code>useReducer</code> hook in action, we will build a very simple counter app that increments by 1 when an increment button is clicked and decrements by 1 when a decrement button is clicked.</p>
<p>Firstly, let us take a closer look at the important  <code>reducer</code> function. This function determines how the state gets updated and contains all the logic through which the next state will be calculated. </p>
<p>Basically, reducers house the logic that is usually placed inside of an event handler when using <code>useState</code>. This makes it easier to read and debug when you are not getting desired results. A quick look at the reducer function can save you the stress.</p>
<p>The reducer function is always declared outside of your component and takes in a current <code>state</code> and <code>action</code> as arguments.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">reducer</span>(<span class="hljs-params">state, action</span>) </span>{
}
</code></pre>
<p>An <code>action</code> is an object that typically has a <code>type</code> property which identifies a specific action. Actions describe what happens and contains information necessary for the reducer to update the state.</p>
<p>Conditional statements are used to check the action types and perform a specified operation that would return a new state value. Conditional statements like <code>if</code> and <code>switch</code> can be used in reducers.</p>
<h3 id="heading-dispatch-function">Dispatch Function</h3>
<p>This is a function returned by the <code>useReducer</code> hook and is responsible for updating state to a new value. The dispatch function takes the action as its only argument.</p>
<p>We can place the dispatch function inside an event handler function. Remember, actions come with a type property so we have to specify when we call the dispatch function. For our counter app, we have two event handlers that increase and decrease the count.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleIncrement</span>(<span class="hljs-params"></span>) </span>{
    dispatch({ <span class="hljs-attr">type</span>: <span class="hljs-string">"increment"</span> });
  }

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleDecrement</span>(<span class="hljs-params"></span>) </span>{
    dispatch({ <span class="hljs-attr">type</span>: <span class="hljs-string">"decrement"</span> });
  }
</code></pre>
<p>Now, we'll go back to our reducer function and use the <code>switch</code> condition to evaluate the <code>action.type</code> expression.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">reducer</span>(<span class="hljs-params">state, action</span>) </span>{
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">"increment"</span>:
      <span class="hljs-keyword">return</span> { ...state, <span class="hljs-attr">count</span>: state.count + <span class="hljs-number">1</span> };
    <span class="hljs-keyword">case</span> <span class="hljs-string">"decrement"</span>:
      <span class="hljs-keyword">return</span> { ...state, <span class="hljs-attr">count</span>: state.count - <span class="hljs-number">1</span> };
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> <span class="hljs-string">"Unrecognized command"</span>;
  }
}
</code></pre>
<p>In the above code,</p>
<ul>
<li>The <code>reducer</code> function takes both the state and action as an argument.</li>
<li>We conditionally check for a specific case of the <code>action.type</code> expression string.</li>
<li>If true, a shallow copy of the state is taken by the use of the spread operator and the count value in state is evaluated.</li>
<li>A new state is returned after evaluation has been completed.</li>
<li>The <code>default</code> serves a fallback when no matching case is found.</li>
</ul>
<p>The entire logic of our counter app has been done. We can now return our JSX with the state of <code>count</code> to be displayed on the user interface and the handler functions passed to the <code>onClick</code> event handler for the buttons.</p>
<pre><code class="lang-js"><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">h1</span>&gt;</span>Count:{state.count}<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">{handleIncrement}</span>&gt;</span>Increment<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleDecrement}</span>&gt;</span>Decrement<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
</code></pre>
<p>Our counter app is set and the <code>count</code> state will be updated accordingly when the buttons are clicked.</p>
<h2 id="heading-what-happens-behind-the-hood">What Happens Behind the Hood?</h2>
<p>The action of clicking the button triggers a <code>dispatch</code> function that sends an information of <code>type</code> to the reducer function. The dispatching (clicking of the button) causes a re-render of the component. The reducer function conditionally matches the case with the type from the action object and updates the state accordingly after evaluation has taken place.</p>
<p><strong>NOTE</strong>: At dispatch, the reducer function still holds the old value. This means that the dispatch function only updates the state variable for the next render. To check this out, we can log the <code>state</code> and <code>action</code> arguments to the console before the switch statement:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">reducer</span>(<span class="hljs-params">state, action</span>) </span>{
  <span class="hljs-built_in">console</span>.log(state, action);

  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">"increment"</span>:
      <span class="hljs-keyword">return</span> { ...state, <span class="hljs-attr">count</span>: state.count + <span class="hljs-number">1</span> };
    <span class="hljs-keyword">case</span> <span class="hljs-string">"decrement"</span>:
      <span class="hljs-keyword">return</span> { ...state, <span class="hljs-attr">count</span>: state.count - <span class="hljs-number">1</span> };
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> <span class="hljs-string">"Unrecognized command"</span>;
  }
  }
</code></pre>
<p>After clicking the increment button to increase the count twice, here is what is logged to the console:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/Capture.PNG" alt="Image" width="600" height="400" loading="lazy">
<em>state and action type logged to the console</em></p>
<p>The above image shows that, at the first click, there was an action type of <code>increment</code> made and the initial state value was 0. At the second click, the state value updated to 1, and was displayed as the current count state. I hope you get it now.</p>
<p>Enough of the code gibberish, let's look at a real-world example of the reducer function.</p>
<h2 id="heading-real-world-reducer-example">Real-world Reducer Example</h2>
<p>Picture a dispatcher that works for an online shopping company going to a warehouse to get the goods/items they would later distribute to the people that ordered them.</p>
<p>The dispatcher identifies themself and performs an action of claiming the goods meant for dispatch to the warehouse manager. The manager goes to a box that contains orders shipped and locates the goods meant to be given to the dispatcher. The manager also logs into the inventory system and does the evaluations before handing over the goods to the dispatcher.</p>
<p>This scenario can also be translated as:</p>
<ul>
<li>The dispatcher makes a request for an update or triggers a process like the <code>dispatch</code> function. </li>
<li>The dispatcher performs an action of  'claiming goods' like the dispatch <code>action</code> with a <code>type</code> property.</li>
<li>The warehouse manager does the necessary sorting and updating just like the <code>reducer</code> function.</li>
<li>The box that houses all the goods is updated depending on how many are cleared for dispatch. This acts like the <code>state</code> update.</li>
</ul>
<p>I hope this real-world scenario makes the entire process clearer to you.</p>
<p>Take a look at the full code once again and digest the process.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useReducer } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">reducer</span>(<span class="hljs-params">state, action</span>) </span>{
  <span class="hljs-built_in">console</span>.log(state, action);
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">"increment"</span>:
      <span class="hljs-keyword">return</span> { ...state, <span class="hljs-attr">count</span>: state.count + <span class="hljs-number">1</span> };
    <span class="hljs-keyword">case</span> <span class="hljs-string">"decrement"</span>:
      <span class="hljs-keyword">return</span> { ...state, <span class="hljs-attr">count</span>: state.count - <span class="hljs-number">1</span> };
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> <span class="hljs-string">"Unrecognized command"</span>;
  }
}
<span class="hljs-keyword">const</span> initialState = { <span class="hljs-attr">count</span>: <span class="hljs-number">0</span> };
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [state, dispatch] = useReducer(reducer, initialState);

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleIncrement</span>(<span class="hljs-params"></span>) </span>{
    dispatch({ <span class="hljs-attr">type</span>: <span class="hljs-string">"increment"</span> });
  }
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleDecrement</span>(<span class="hljs-params"></span>) </span>{
    dispatch({ <span class="hljs-attr">type</span>: <span class="hljs-string">"decrement"</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">h1</span>&gt;</span>Count:{state.count}<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">{handleIncrement}</span>&gt;</span>Increment<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleDecrement}</span>&gt;</span>Decrement<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
}
</code></pre>
<h2 id="heading-benefits-of-using-the-usereducer-hook">Benefits of Using the <code>useReducer</code> Hook</h2>
<ul>
<li>Helps centralize state logic.</li>
<li>Makes state transitions predictable.</li>
<li>Suitable for complex state management.</li>
<li>Optimizes performance.</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>We have covered what the <code>useReducer</code> hook is, how it compares to <code>useState</code> – similarities and differences, the reducer process and the benefits of using <code>useReducer</code>.</p>
<p>If you found this article helpful, you can <a target="_blank" href="https://buymeacoffee.com/timothyolanrewaju">buy me a coffee</a>.</p>
<p>You can also connect with me on <a target="_blank" href="http://linkedin.com/in/timothy-olanrewaju750">LinkedIn</a> .</p>
<p>See you on the next one!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ React Hooks – How to Use the useState & useEffect Hooks in Your Project ]]>
                </title>
                <description>
                    <![CDATA[ Hooks allow function components to have access to state and other React features, such as lifecycle methods. These Hook features were introduced to React version 16.8. One of the interesting things about the Hook features is that they let you use Rea... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-the-usestate-and-useeffect-hooks-in-your-project/</link>
                <guid isPermaLink="false">66d45e0c47a8245f78752a26</guid>
                
                    <category>
                        <![CDATA[ hooks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ react hooks ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Okoro Emmanuel Nzube ]]>
                </dc:creator>
                <pubDate>Fri, 08 Mar 2024 15:37:42 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/03/React-JS-Hooks.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hooks allow function components to have access to state and other React features, such as lifecycle methods. These Hook features were introduced to React version 16.8.</p>
<p>One of the interesting things about the Hook features is that they let you use React without classes. This, in turn, helps simplify your codebase and helps you write cleaner and more intuitive code.</p>
<p>In this article, you will learn how to make use of the common Hooks in your project.</p>
<h2 id="heading-react-hooks-benefits">React Hooks Benefits</h2>
<p>Let's go over some of the reasons why you might want to use Hooks in your project:</p>
<ul>
<li><p><strong>Easy to use and understand:</strong> With Hooks, you can write more straightforward code. These Hook commands can only be written inside a functional component.</p>
</li>
<li><p><strong>Reusable code:</strong> Hooks allow you to reuse a particular logic used in one component across multiple other components.</p>
</li>
<li><p><strong>Better optimization performance:</strong> Hooks offer a more efficient approach to utilizing React functionalities like state and lifecycle functions, resulting in improved performance as compared to class components in some situations.</p>
</li>
</ul>
<h2 id="heading-different-types-of-react-hooks">Different Types of React Hooks</h2>
<p>The React Hook features are of different types, ranging from the <code>useState</code>, <code>useEffect</code>, <code>useRef</code>, <code>useReducer</code>, and so on.</p>
<h2 id="heading-react-hook-rules">React Hook Rules</h2>
<p>There are a few important rules when it comes to the React Hook features that should be strictly followed. Let's go over them in the following sections.</p>
<h3 id="heading-hooks-should-be-called-inside-a-react-function">Hooks should be called inside a React function</h3>
<p>Hooks should not be used inside a class component – they can and should only be called inside the React function.</p>
<p>This first rule essentially specifies that a Hook component should not be found in a class component, but in a functional component.</p>
<p>Here is the wrong way of implementing the Hook feature:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> React, {useState} <span class="hljs-keyword">from</span> react;

<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">Component</span> </span>{
 <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);

  render() {
    <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>Hello, I am a Class Component!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</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>And here is the correct way of implementing the Hook feature:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</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> [userName, setUsername] = useState(<span class="hljs-string">''</span>);

  };

  <span class="hljs-keyword">return</span> ( Your JSX code goes <span class="hljs-keyword">in</span> here.....);
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>The code example above shows a proper way of using a Hook feature.</p>
<p>If you use a Hook feature in a class component, just like in the first example, your code will raise an error. Therefore, you can only implement a Hook inside a function component.</p>
<h3 id="heading-hooks-can-only-be-called-at-the-top-level-of-a-component">Hooks can only be called at the top level of a component</h3>
<p>You can only implement/call a React Hook at the top level of a component before any other code.</p>
<p>Using the code from the previous section as an example, you can see that immediately after <code>function App ()</code>.</p>
<p>The next thing that comes is the Hook command – in that example we used the <code>useState</code> Hook. That is what the second rule is all about.</p>
<h3 id="heading-hooks-cannot-be-used-in-a-conditional-statement">Hooks cannot be used in a conditional statement</h3>
<p>We have different types of conditional statements/rendering ranging from <code>if</code>, <code>else</code>, and so on.</p>
<p>The above rule means that conditionals cannot be applied directly to Hooks. This is the case because Hooks are called in the same order on every render of a functional component.</p>
<p>You can conditionally run Hooks within a functional component, but for this to work, this condition must be determined by top-level logic and should not be nested within any other blocks or components.</p>
<p>The reason for this is because Hooks need to be invoked at the highest level of the component, rather than under conditions, loops, or nested functions.</p>
<p>Here is an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ConditionalEffectComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [isMounted, setIsMounted] = useState(<span class="hljs-literal">false</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">if</span> (isMounted) {
      <span class="hljs-comment">// Perform some effect when the component is mounted</span>
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Component mounted'</span>);
    }
  }, [isMounted]); <span class="hljs-comment">// Dependency array ensures effect runs when isMounted changes</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">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setIsMounted(!isMounted)}&gt;
        {isMounted ? 'Unmount' : 'Mount'}
      <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> ConditionalEffectComponent;
</code></pre>
<p>From the example above, the <code>useEffect</code> hook is executed conditionally dependent on the value of the <code>isMounted</code> state variable.</p>
<p>Clicking the button causes the value of <code>isMounted</code> to alternate, either activating or deactivating the effect depending on the updated value.</p>
<p>This is deemed appropriate because the Hook is invoked at the highest level of the component and its condition is determined by the overarching logic within the component.</p>
<h2 id="heading-how-to-use-the-usestate-hook">How to Use the useState Hook</h2>
<p>The React <code>useState</code> Hook enables you to have state variables in functional components.</p>
<p>To make use of the state Hook, you must first import it into your project by using the <code>import</code> command.</p>
<p>The way <code>useState</code> works is that it gives us two variables. The first variable is known as the value of the state, and the second variable is a function used to update the state.</p>
<p>Here is an example of how to go about this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> <span class="hljs-string">'./App.css'</span>
<span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{ 

    <span class="hljs-keyword">const</span> [count, setCount] = useState(<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>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>You clicked {count} times<span class="hljs-tag">&lt;/<span class="hljs-name">p</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> setCount(count + 1)}&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> App;
</code></pre>
<p>From the code example above, you can see that the state Hook was used in a functional component and not a class component.</p>
<p><code>count</code> and <code>setCount</code> are the two variables of the state Hook, where <code>count</code> is the current value of the state and <code>setCount</code> is used to update the value of the state. Therefore, whenever the button is clicked, <code>setCount</code> will update the value of the count.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/R1.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>How useState Hook works</em></p>
<h2 id="heading-how-to-use-the-useeffect-hook">How to Use the useEffect Hook</h2>
<p>The <code>useEffect</code> hook in React is like a handy tool for functional components. It helps manage tasks that aren't directly related to showing stuff on the screen, like fetching data from the internet, retrieving data from API endpoints, or setting up timers. It can be used to update components even after they've been shown, making your app more dynamic.</p>
<p>Here's a basic example of how <code>useEffect</code> is used to fetch data from an API endpoint:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</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> [data, setData] = useState(<span class="hljs-literal">null</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> fetchData = <span class="hljs-keyword">async</span> () =&gt; {
      <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://api.example.com/data'</span>);
        <span class="hljs-keyword">const</span> jsonData = <span class="hljs-keyword">await</span> response.json();
        setData(jsonData);
      } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error fetching data:'</span>, error);
      }
    };

    fetchData(); <span class="hljs-comment">// Call the fetchData function when the component mounts or updates</span>

    <span class="hljs-comment">// Cleanup function (optional) to handle unsubscriptions or resource cleanup</span>
    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> {
      <span class="hljs-comment">// Cleanup logic here, if needed</span>
    };
  }, []); <span class="hljs-comment">// Empty dependency array means the effect runs only once after the initial render</span>

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      {/* Render the fetched data */}
      {data &amp;&amp; (
        <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
          {data.map(item =&gt; (
            <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{item.id}</span>&gt;</span>{item.name}<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">div</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> MyComponent;
</code></pre>
<p>In the code example above, <code>MyComponent</code> is a functional component which utilizes React hooks, specifically <code>useState</code> and <code>useEffect</code>, to handle state management and execute side effects. The <code>useState</code> hook is used to initialize a state variable called <code>data</code>. This variable will store the data retrieved from an API endpoint.</p>
<p>The <code>useEffect</code> hook is used to request data from the API endpoint once the component initially renders. Within the <code>useEffect</code>, an asynchronous function <code>fetchData</code> is defined to fetch JSON data from the specified API endpoint using the fetch API.</p>
<p>If the data fetching is successful, the returned JSON data is saved in the data state variable using the <code>setData</code> function supplied by the <code>useState</code> hook.</p>
<p>The <code>useEffect</code> hook also optionally returns a cleaning function, which is currently empty but can be used for any necessary cleanup logic.</p>
<p>In the component's JSX, the fetched data is conditionally rendered. If the data is not null, a list <code>&lt;ul&gt;</code> is produced using items extracted from the data array using map.</p>
<p>Finally, the <code>MyComponent</code> function is exported as the default export from the module, allowing it to be imported and utilized in other sections.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>As a developer, React Hooks are a very useful and powerful tool for functional components that make your work easy.</p>
<p>I believe that at this point you now know what a React Hook is and how to use the most popular ones.</p>
<p>Thanks for reading, and happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Create a Custom React Hook – a Hands-on Tutorial ]]>
                </title>
                <description>
                    <![CDATA[ If you have been working with React, I bet you've had the opportunity to use hooks. But have you ever tried to create your own hook?  Today I will help you create your first custom hook and explain how they can improve your codebase. Why Create Custo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-create-custom-react-hooks/</link>
                <guid isPermaLink="false">66bc4d01e35f27b3539506e4</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ react hooks ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Matéu.sh ]]>
                </dc:creator>
                <pubDate>Wed, 14 Feb 2024 17:39:52 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/Custom-hooks.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you have been working with React, I bet you've had the opportunity to use hooks. But have you ever tried to create your own hook? </p>
<p>Today I will help you create your first custom hook and explain how they can improve your codebase.</p>
<h2 id="heading-why-create-custom-hooks">Why Create Custom Hooks?</h2>
<p>You might be wondering – why would I even want to create new React hook? In the end, React has all the essential hooks in place and anything else seems slightly excessive. That's true React comes with many powerful hooks, but did you know that custom hooks can improve the quality of your code? </p>
<p>Imagine you have a piece of React code that's used across many components. As a programmer, you don't want to repeat yourself, and you make repeated code reusable as much as possible. That's why it's a good idea to wrap those snippets into utilities, components, or custom hooks.</p>
<p>Crafting your own hooks will not only simplify your components, but also significantly reduce the size of your codebase. Remember, less code typically means better readability and lower code complexity, too.</p>
<p>I hope I have you "hooked" now – pun intended.</p>
<h2 id="heading-prerequisites"><strong>🛠️ P</strong>rerequisites<em>**</em></h2>
<p>Before you read this guide, you need to be familiar with React. Don't get me wrong – you don't need to be an expert, but some understanding of the basics are necessary. </p>
<p>If you don't feel like a strong enough React dev, you might consider enrolling in <a target="_blank" href="https://www.udemy.com/course/2048-in-react-and-nextjs/?referralCode=AC3FD6336BAB9C402106">my Udemy course</a> where you will learn React 18 by creating a 2048 game from scratch. You can find more details and a discount code at the end of this tutorial.</p>
<p>Also, you can check out <a target="_blank" href="https://www.freecodecamp.org/news/learn-react-key-concepts/">this free tutorial</a> where you'll learn the key concepts you need to get started with React.</p>
<h2 id="heading-your-first-custom-hook-usepreviousprops">🪝 Your First Custom Hook – <code>usePreviousProps</code></h2>
<p>In my articles, I'm always trying to use real world examples – and this guide will not be any different. We will create a hook responsible for tracking previous values of component props. This means we will build a custom hook called <code>usePreviousProps</code> from scratch. </p>
<p>One of the most common use cases for a hook like this is when you're dealing with animations. For instance, imagine that you need to highlight a newly created element. How could you determine if it's new without comparing current values to previous ones? That's where our new hook comes into play.</p>
<p>The benefits of a custom hook like ours might be a bit vague, but it's a really powerful tool. Literally, the custom <code>usePreviousProps</code> hook we'll create today is used in some of my open source projects, and even a few production-grade apps I've built. So you can be sure this hook has a real use case, and it only takes 12 lines to implement.</p>
<p>Now let's get our hands dirty!</p>
<h2 id="heading-how-to-create-a-custom-hook">🪚 How to Create a Custom Hook</h2>
<p>First, we need to create a new file in the <code>hooks</code> directory of your project – I decided to call it <code>use-previous-props.js</code>. </p>
<p>Keep in mind that React hooks rarely use JSX syntax (HTML), which is why we are using the <code>.js</code> extension. If you need to enable JSX syntax need to change the extension to <code>.jsx</code>. But think twice before doing this – if you really need JSX, you should probably crate a standalone component instead of a hook.</p>
<pre><code class="lang-js"><span class="hljs-comment">// file: hooks/use-previous-props.js</span>

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

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">usePreviousProps</span>(<span class="hljs-params">value</span>) </span>{
  <span class="hljs-keyword">const</span> ref = useRef();

  useEffect(<span class="hljs-function">() =&gt;</span> {
    ref.current = value;
  });

  <span class="hljs-keyword">return</span> ref.current;
}
</code></pre>
<p>As you can see, our hook is very similar to a regular functional component. The only difference is the <code>return</code> statement – it returns a JavaScript value instead of an HTML element.</p>
<p>React hooks often return values, functions, or both. For example, the <code>useState</code> hook returns an array with two elements: the current state value and a function to update that value. </p>
<p>Now let me explain how the <code>usePreviousProps</code> hook actually works:</p>
<ul>
<li><code>const ref = useRef()</code> is used to persist the reference across re-renders of the component. In our case, we will use it to store the previous value. </li>
<li>The <code>useEffect</code> hook will update <code>ref.current</code> value whenever the component re-renders. This means that when <code>value</code> changes, the <code>ref.current</code> value will be updated to store the most recent value of the prop. Importantly, all of this happens after the component finishes rendering, so it stores the previous value during the re-render.</li>
<li><code>return ref.current</code> returns the value from the <code>ref</code> reference.</li>
</ul>
<p>Now our custom <code>usePreviousProps</code> hook is ready to use!</p>
<h2 id="heading-how-to-use-a-custom-hook">😎 How to Use a Custom Hook</h2>
<p>Last week I published the tutorial <a target="_blank" href="https://www.freecodecamp.org/news/create-animations-in-react/">How to Create Animations in React 18</a>.</p>
<p>If you didn't read my last tutorial, it includes the custom <code>usePreviousProps</code> hook to create highlighting animations:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/hightlight-3.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Highlighting animation</em></p>
<p>Here is the code responsible for this animation:</p>
<pre><code class="lang-jsx"><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">Tile</span>(<span class="hljs-params">{ value }</span>) </span>{
  <span class="hljs-keyword">const</span> [scale, setScale] = useState(<span class="hljs-number">1</span>);

  <span class="hljs-keyword">const</span> previousValue = usePreviousProps(value);
  <span class="hljs-keyword">const</span> hasChanged = previousValue !== value;

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">if</span> (hasChanged) {
      setScale(<span class="hljs-number">1.1</span>);
      <span class="hljs-built_in">setTimeout</span>(
          <span class="hljs-function">() =&gt;</span> setScale(<span class="hljs-number">1</span>), 
          <span class="hljs-number">100</span> <span class="hljs-comment">/* 100ms == 0.1s */</span>
      );
    }
  }, [hasChanged, setScale]);

  <span class="hljs-keyword">const</span> style = {
    <span class="hljs-attr">transform</span>: <span class="hljs-string">`scale(<span class="hljs-subst">${scale}</span>)`</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">"tile"</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{style}</span>&gt;</span>
      {value}
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};
</code></pre>
<p>Let's focus on this line: <code>const previousValue = usePreviousProps(value)</code>.</p>
<p>Here, <code>previousValue</code> contains the previous value for this component. If it's a new component it returns <code>undefined</code>.</p>
<p>On the next line, the <code>hasChanged</code> constant helps determine if the component should be highlighted. If it's new and returned <code>undefined</code> earlier, it triggers the highlighting animation.</p>
<p>A few lines later, I declared the <code>useEffect</code> hook that will check if a component has changed its value. If that happened, React will execute the highlighting animation.</p>
<h2 id="heading-summary"><strong>🏁 Summary</strong></h2>
<p>Today you've learned that React hooks are fairly similar to functional components. The only difference is their output, where they return JavaScript values, arrays, or functions rather than JSX elements.</p>
<p>As you can see, creating custom hooks isn't rocket science, and I hope I've inspired you to experiment and create one of your own.</p>
<p>If this article helped you, please share it on your social media or give me a <a target="_blank" href="https://twitter.com/msokola">shout-out on Twitter</a>. Thank you!</p>
<h2 id="heading-would-you-like-to-build-your-own-2048-game"><strong>🏫 </strong>Would You Like to Build Your Own 2048 Game?<em>**</em></h2>
<p>If you want to improve your React skills, consider joining my online course on Udemy. I will help you to get started with React 18 by building a fully-functional 2048 Game. I believe creating games makes learning more fun, and you'll have something cool to show your friends. </p>
<p>Also, I'm giving a 50% discount for freeCodeCamp readers. Just use the code <strong>50DISCOUNT</strong> to enroll.</p>
<p>👇👇👇👇</p>
<h3 id="heading-join-my-react-18-course-on-udemyhttpswwwudemycomcourse2048-in-react-and-nextjsreferralcodeac3fd6336bab9c402106"><strong>🧑‍🎓 Join my <a target="_blank" href="https://www.udemy.com/course/2048-in-react-and-nextjs/?referralCode=AC3FD6336BAB9C402106">React 18 course on Udemy</a></strong></h3>
<p>What you'll learn:</p>
<ul>
<li>How to build 2048 game with React 18 and Next.js.</li>
<li>Essential React hooks such as useState, useRef, useCallback, useEffect, and many more.</li>
<li>Managing state using Reducer and React Context.</li>
<li>How to create responsive mobile apps that support touch events (like mobile swiping).</li>
<li>Integrate TypeScript into your React projects.</li>
<li>Testing React apps.</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use setTimeout in React Using Hooks ]]>
                </title>
                <description>
                    <![CDATA[ React has emerged as a powerful and widely used JavaScript library for building user interfaces. Its component-based architecture allows developers to create modular and reusable code, making it easier to manage and maintain complex applications.  On... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-settimeout-in-react-using-hooks/</link>
                <guid isPermaLink="false">66c4c3e8bd556981b1bdc43b</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ react hooks ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joan Ayebola ]]>
                </dc:creator>
                <pubDate>Wed, 06 Dec 2023 23:37:13 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/12/Blue---white-company-profile-presentation--1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>React has emerged as a powerful and widely used JavaScript library for building user interfaces. Its component-based architecture allows developers to create modular and reusable code, making it easier to manage and maintain complex applications. </p>
<p>One common requirement in web development projects is the ability to delay the execution of certain tasks. That's where <code>setTimeout</code> comes into play. </p>
<p>Consider scenarios where you want to create smooth transitions, display loading spinners, or implement animations. In these cases, delaying the execution of specific actions allows you to control the timing of visual elements, providing a more polished and user-friendly interface.</p>
<p>In this article, we'll explore how to leverage <code>setTimeout</code> in React, specifically using React Hooks. React Hooks are functions that let you use state and other React features in functional components. If you're new to React Hooks or just want to learn more about using <code>setTimeout</code> effectively, you're in the right place.</p>
<p>Here's what we'll cover:</p>
<ol>
<li><a class="post-section-overview" href="#heading-how-does-settimeout-work">How Does <code>setTimeout</code> Work?</a></li>
<li><a class="post-section-overview" href="#heading-set-up-a-react-project">Set Up a React Project</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-settimeout-in-functional-components">How to Use <code>setTimeout</code> in Functional Components</a></li>
<li><a class="post-section-overview" href="#heading-how-to-handle-user-interactions-with-settimeout">How to Handle User Interactions with <code>setTimeout</code></a></li>
<li><a class="post-section-overview" href="#heading-how-to-handle-dynamic-delays-with-settimeout">How to Handle Dynamic Delays with <code>setTimeout</code></a></li>
<li><a class="post-section-overview" href="#heading-how-to-handle-multiple-settimeouts-in-sequence">How to Handle Multiple <code>setTimeout</code>s in Sequence</a></li>
<li><a class="post-section-overview" href="#heading-how-to-handle-multiple-settimeouts-in-async-operations">How to Handle Multiple <code>setTimeout</code>s in Async Operations</a></li>
<li><a class="post-section-overview" href="#heading-how-to-cancel-settimeout-functions">How to Cancel <code>setTimeout</code> Functions</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-settimeout-with-promises">How to Use <code>setTimeout</code> with Pro</a>mises</li>
<li><a class="post-section-overview" href="#heading-how-to-use-settimeout-with-asyncawait">How to Use <code>setTimeout</code> with <code>async/await</code></a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<h2 id="heading-how-does-settimeout-work">How Does <code>setTimeout</code> Work?</h2>
<p>Before we dive into using <code>setTimeout</code> in a React application, let's briefly understand what <code>setTimeout</code> is and how it works in JavaScript.</p>
<p><code>setTimeout</code> is a built-in JavaScript function that allows you to schedule the execution of a function after a specified amount of time. Its basic syntax looks like this:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">setTimeout</span>(callback, delay);
</code></pre>
<ul>
<li><code>callback</code>: A function to be executed after the specified delay.</li>
<li><code>delay</code>: The time (in milliseconds) to wait before executing the callback function.</li>
</ul>
<p>For example, the following code snippet will log "Hello, World!" to the console after a delay of 2000 milliseconds (2 seconds):</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello, World!"</span>);
}, <span class="hljs-number">2000</span>);
</code></pre>
<p>Now that we have a basic understanding of <code>setTimeout</code>, let's see how we can integrate it with React using Hooks.</p>
<h2 id="heading-set-up-a-react-project">Set Up a React Project</h2>
<p>To follow along with the examples in this article, you'll need a basic understanding of React, and Node.js installed on your machine. </p>
<p>For those already familiar with setting up a React project, you can skip the following steps. If not, you can create a new React project using Create React App with the following commands (or use the build tool of your choice):</p>
<pre><code class="lang-bash">npx create-react-app my-react-app
<span class="hljs-built_in">cd</span> my-react-app
npm start
</code></pre>
<p>Replace "my-react-app" with your preferred project name. The <code>npm start</code> command launches the development server, and you can access your React application at <code>http://localhost:3000</code>.</p>
<h2 id="heading-how-to-use-settimeout-in-functional-components">How to Use <code>setTimeout</code> in Functional Components</h2>
<p>In React, functional components are a lightweight way to define UI components. With the introduction of Hooks in React 16.8, functional components can now use state and other features that were previously exclusive to class components. </p>
<p>Let's start by creating a simple functional component and using <code>setTimeout</code> within it.</p>
<p>Open the <code>src/App.js</code> file and replace its contents with the following code:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> DelayedMessage = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [message, setMessage] = useState(<span class="hljs-string">''</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-comment">// Use setTimeout to update the message after 2000 milliseconds (2 seconds)</span>
    <span class="hljs-keyword">const</span> timeoutId = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      setMessage(<span class="hljs-string">'Delayed message after 2 seconds!'</span>);
    }, <span class="hljs-number">2000</span>);

    <span class="hljs-comment">// Cleanup function to clear the timeout if the component unmounts</span>
    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">clearTimeout</span>(timeoutId);
  }, []); <span class="hljs-comment">// Empty dependency array ensures the effect runs only once</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>{message}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</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">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> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">DelayedMessage</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've created a functional component called <code>DelayedMessage</code>. Inside this component, we use the <code>useState</code> hook to manage the state of the <code>message</code> variable. The <code>useEffect</code> hook is used to handle side effects, such as asynchronous operations, in functional components.</p>
<p>Within the <code>useEffect</code> hook, we use <code>setTimeout</code> to update the <code>message</code> state after a delay of 2000 milliseconds. We also provide a cleanup function using <code>clearTimeout</code> to ensure that the timeout is cleared if the component unmounts before the timeout completes.</p>
<p>Now, when you run your React application (<code>npm start</code>), you should see the message "Delayed message after 2 seconds!" rendered on the screen after a brief delay.</p>
<h2 id="heading-how-to-handle-user-interactions-with-settimeout">How to Handle User Interactions with <code>setTimeout</code></h2>
<p>In the previous example, we explored a scenario where <code>setTimeout</code> was used to simulate a delayed action triggered by a button click. While this demonstrates the basic usage of <code>setTimeout</code> in response to user interaction, it's essential to emphasize the importance of handling user input validation in real-world applications.</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> DelayedAction = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [actionStatus, setActionStatus] = useState(<span class="hljs-string">'Idle'</span>);
  <span class="hljs-keyword">const</span> [delayDuration, setDelayDuration] = useState(<span class="hljs-number">3000</span>);

  <span class="hljs-keyword">const</span> handleButtonClick = <span class="hljs-function">() =&gt;</span> {
    setActionStatus(<span class="hljs-string">'Action in progress...'</span>);

    <span class="hljs-comment">// Use setTimeout to simulate a delayed action</span>
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      setActionStatus(<span class="hljs-string">'Action completed!'</span>);
    }, delayDuration);
  };

  <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>Status: {actionStatus}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleButtonClick}</span>&gt;</span>Trigger Delayed Action<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
        <span class="hljs-attr">type</span>=<span class="hljs-string">"number"</span>
        <span class="hljs-attr">value</span>=<span class="hljs-string">{delayDuration}</span>
        <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setDelayDuration(parseInt(e.target.value, 10))}
      /&gt;
    <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> DelayedAction;
</code></pre>
<h3 id="heading-importance-of-user-input-validation">Importance of User Input Validation</h3>
<p>In scenarios where user input directly influences the behavior of <code>setTimeout</code> or other time-related operations, validating that input becomes crucial. Failing to validate user input can lead to unexpected behavior, potential errors, or even security vulnerabilities.</p>
<p>In the code snippet above, we have an input field that allows users to specify the delay duration in milliseconds. It's essential to note that the <code>setDelayDuration</code> function is wrapped with <code>parseInt</code> to ensure that the input is converted to a valid integer. This step helps prevent issues arising from non-numeric or negative input values.</p>
<pre><code class="lang-jsx">&lt;input
  type=<span class="hljs-string">"number"</span>
  value={delayDuration}
  onChange={<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> setDelayDuration(<span class="hljs-built_in">parseInt</span>(e.target.value, <span class="hljs-number">10</span>))}
/&gt;
</code></pre>
<p>By validating user input, you can ensure that the delay duration remains within expected boundaries, mitigating the risk of unexpected behavior. </p>
<p>Incorporating input validation practices is a fundamental aspect of building robust and secure React applications, especially when dealing with asynchronous operations tied to user actions.</p>
<h2 id="heading-how-to-handle-dynamic-delays-with-settimeout">How to Handle Dynamic Delays with <code>setTimeout</code></h2>
<p>In some cases, you may want to dynamically set the delay duration based on certain conditions or user input. Let's modify the previous example to allow users to input the delay duration through a text input field.</p>
<p>Update the <code>src/App.js</code> file with the following code:</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> DynamicDelayAction = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [actionStatus, setActionStatus] = useState(<span class="hljs-string">'Idle'</span>);
  <span class="hljs-keyword">const</span> [delayDuration, setDelayDuration] = useState(<span class="hljs-number">3000</span>);

  <span class="hljs-keyword">const</span> handleButtonClick = <span class="hljs-function">() =&gt;</span> {
    setActionStatus(<span class="hljs-string">'Action in progress...'</span>);

    <span class="hljs-comment">// Use setTimeout with dynamically set delay duration</span>
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      setActionStatus(<span class="hljs-string">'Action completed!'</span>);
    }, delayDuration);
  };

  <span class="hljs-keyword">const</span> handleInputChange = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> value = <span class="hljs-built_in">parseInt</span>(e.target.value, <span class="hljs-number">10</span>);
    setDelayDuration(<span class="hljs-built_in">isNaN</span>(value) ? <span class="hljs-number">0</span> : value); <span class="hljs-comment">// Set delayDuration to 0 if NaN</span>
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Action Status: {actionStatus}<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>
        Delay Duration (milliseconds):
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{delayDuration}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleInputChange}</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleButtonClick}</span>&gt;</span>Trigger Delayed Action<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-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> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">DynamicDelayAction</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've introduced a text input field to allow users to input the delay duration in milliseconds. The <code>delayDuration</code> state variable is updated based on user input, and the <code>handleInputChange</code> function ensures that the input is a valid integer.</p>
<p>The <code>handleButtonClick</code> function then uses <code>setTimeout</code> with the dynamically set delay duration. Users can now specify the delay duration through the text input field, giving them control over when the action will be completed.</p>
<p><strong>Note:</strong> While using <code>setTimeout</code> with dynamically set delays provides flexibility, it's essential to be mindful of potential performance implications. When delays are frequently updated based on user input or other dynamic factors, it may lead to a higher frequency of timer creation and destruction.</p>
<p>Creating and clearing timers excessively can impact the overall performance of your application, especially if the delays are very short. Consider optimizing your code or exploring alternative approaches, such as debouncing user input or using a more sophisticated scheduling mechanism, if you encounter performance issues.</p>
<h2 id="heading-how-to-handle-multiple-settimeouts-in-sequence">How to Handle Multiple <code>setTimeout</code>s in Sequence</h2>
<p>In some scenarios, you might need to execute multiple <code>setTimeout</code> functions in sequence, creating a chain of delayed actions. Let's explore how to achieve this by creating a component that displays a countdown with multiple steps.</p>
<p>Update the <code>src/App.js</code> file with the following code:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> Countdown = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [countdown, setCountdown] = useState(<span class="hljs-number">5</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> countdownInterval = <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-comment">// Decrease the countdown value every second</span>
      setCountdown(<span class="hljs-function">(<span class="hljs-params">prevCountdown</span>) =&gt;</span> prevCountdown - <span class="hljs-number">1</span>);
    }, <span class="hljs-number">1000</span>);

    <span class="hljs-comment">// Cleanup function to clear the interval when the component unmounts</span>
    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">clearInterval</span>(countdownInterval);
  }, []); <span class="hljs-comment">// Empty dependency array ensures the effect runs only once</span>

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-comment">// Use setTimeout to reset the countdown after it reaches 0</span>
    <span class="hljs-keyword">if</span> (countdown === <span class="hljs-number">0</span>) {
      <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
        setCountdown(<span class="hljs-number">5</span>); <span class="hljs-comment">// Reset the countdown to 5 seconds</span>
      }, <span class="hljs-number">2000</span>); <span class="hljs-comment">// Delay before resetting (2 seconds)</span>
    }
  }, [countdown]); <span class="hljs-comment">// Effect re-runs whenever countdown changes</span>

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Countdown: {countdown}<span class="hljs-tag">&lt;/<span class="hljs-name">h2</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">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> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Countdown</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've created a <code>Countdown</code> component that displays a countdown value. The countdown starts from 5 and decreases by 1 every second using <code>setInterval</code>. When the countdown reaches 0, a <code>setTimeout</code> function is used to reset the countdown to 5 after a delay of 2000 milliseconds (2 seconds).</p>
<p>The key takeaway here is the use of multiple <code>useEffect</code> hooks. The first <code>useEffect</code> initializes the countdown interval, and the cleanup function ensures that the interval is cleared when the component unmounts. The second <code>useEffect</code> monitors the <code>countdown</code> state and triggers the countdown reset when it reaches 0.</p>
<p>By running the application, you'll observe the countdown resetting to 5 after reaching 0, creating a cyclic sequence of delayed actions.</p>
<h2 id="heading-how-to-handle-multiple-settimeouts-in-async-operations">How to Handle Multiple <code>setTimeout</code>s in Async Operations</h2>
<p>The use of multiple <code>useEffect</code> hooks is crucial for managing asynchronous actions in a controlled manner. Each <code>useEffect</code> hook serves a specific purpose.</p>
<p><strong>Countdown Initialization</strong>: The first <code>useEffect</code> initializes the countdown interval using <code>setInterval</code>. By having a dedicated <code>useEffect</code> for this initialization, we ensure that the interval is set up only once when the component mounts. The cleanup function associated with this <code>useEffect</code> clears the interval when the component is unmounted, preventing memory leaks.</p>
<p><strong>Countdown Reset</strong>: The second <code>useEffect</code> monitors the <code>countdown</code> state and triggers the countdown reset when it reaches 0. This separation of concerns enhances code readability and maintainability. If both functionalities were combined into a single <code>useEffect</code>, it could lead to a less organized and harder-to-understand code structure.</p>
<p>Using multiple <code>useEffect</code> hooks with focused responsibilities promotes better code organization and makes it easier to reason about the asynchronous behavior in your component. </p>
<p>Consider a slideshow component where each image is displayed for a specific duration before transitioning to the next one. By chaining multiple <code>setTimeout</code> functions, you can create a smooth and automated slideshow experience for users.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> startSlideshow = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-comment">// Display first image</span>
  }, <span class="hljs-number">0</span>);

  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-comment">// Display second image after a delay</span>
  }, <span class="hljs-number">3000</span>);

  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-comment">// Display third image after a delay</span>
  }, <span class="hljs-number">6000</span>);
  <span class="hljs-comment">// ...</span>
};
</code></pre>
<p>This sequential execution pattern allows you to orchestrate the timing of different actions, providing a more controlled and organized user experience</p>
<h2 id="heading-how-to-cancel-settimeout-functions">How to Cancel <code>setTimeout</code> Functions</h2>
<p>Cancelling a <code>setTimeout</code> function is essential to preventing unintended behavior, especially when dealing with dynamic delays or component unmounting. The <code>clearTimeout</code> function can be used to cancel a scheduled timeout.</p>
<p>Consider the following example where a timeout is set to update a message after a delay:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> DelayedMessage = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [message, setMessage] = useState(<span class="hljs-string">''</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> timeoutId = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      setMessage(<span class="hljs-string">'Delayed message after 2 seconds!'</span>);
    }, <span class="hljs-number">2000</span>);

    <span class="hljs-comment">// Cleanup function to clear the timeout if the component unmounts</span>
    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">clearTimeout</span>(timeoutId);
  }, []); <span class="hljs-comment">// Empty dependency array ensures the effect runs only once</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>{message}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</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> DelayedMessage;
</code></pre>
<p>In this example, the <code>clearTimeout</code> function is used in the cleanup function of the <code>useEffect</code> hook. If the component unmounts before the timeout completes, the cleanup function ensures that the timeout is cleared, preventing the update of state on an unmounted component.</p>
<h2 id="heading-how-to-use-settimeout-with-promises">How to Use <code>setTimeout</code> with Promises</h2>
<p>JavaScript's <code>setTimeout</code> can be combined with Promises to create more readable and flexible asynchronous code. The <code>setTimeout</code> function itself doesn't return a Promise, but we can wrap it in a Promise to leverage <code>async/await</code> syntax.</p>
<p>Consider the following example:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> delay = <span class="hljs-function">(<span class="hljs-params">milliseconds</span>) =&gt;</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> <span class="hljs-built_in">setTimeout</span>(resolve, milliseconds));

<span class="hljs-keyword">const</span> exampleFunction = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Start'</span>);
  <span class="hljs-keyword">await</span> delay(<span class="hljs-number">2000</span>);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'After 2 seconds'</span>);
};

exampleFunction();
</code></pre>
<p>In this example, the <code>delay</code> function returns a Promise that resolves after the specified number of milliseconds. The <code>exampleFunction</code> uses <code>async/await</code> to wait for the delay to complete before moving on to the next step. This pattern is especially useful when dealing with asynchronous operations that involve timeouts.</p>
<h2 id="heading-how-to-use-settimeout-with-asyncawait">How to Use <code>setTimeout</code> with <code>async/await</code></h2>
<p>Combining <code>setTimeout</code> with <code>async/await</code> allows for cleaner and more readable asynchronous code. While <code>setTimeout</code> itself doesn't directly return a Promise, we can wrap it in a Promise to await the delay.</p>
<p>Consider the following example:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> delay = <span class="hljs-function">(<span class="hljs-params">milliseconds</span>) =&gt;</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> <span class="hljs-built_in">setTimeout</span>(resolve, milliseconds));

<span class="hljs-keyword">const</span> exampleFunction = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Start'</span>);
  <span class="hljs-keyword">await</span> delay(<span class="hljs-number">2000</span>);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'After 2 seconds'</span>);
};

exampleFunction();
</code></pre>
<p>In this example, the <code>delay</code> function returns a Promise that resolves after the specified number of milliseconds. The <code>exampleFunction</code> uses <code>async/await</code> to wait for the delay to complete before moving on to the next step. </p>
<p>This pattern is especially useful when dealing with asynchronous operations that involve timeouts.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this guide, we've covered the basics of using <code>setTimeout</code> in a React application using functional components and React Hooks. </p>
<p>We started with a simple example of displaying a delayed message and gradually explored more complex scenarios, including handling user interaction, dynamically setting delay durations, and chaining multiple <code>setTimeout</code> functions in sequence.</p>
<p>Understanding how to use <code>setTimeout</code> effectively in React can enhance your ability to create responsive and interactive user interfaces. By combining the power of React Hooks with <code>setTimeout</code>, you can implement various asynchronous behaviors in a clean and maintainable way.</p>
<p>As you continue your journey with React development, consider exploring other React Hooks and additional JavaScript concepts to broaden your skills. Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use React Hooks – useEffect, useState, and useContext Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ React is a powerful JavaScript library for building user interfaces. And it has undergone significant changes over the years.  One of the most noteworthy additions is the introduction of hooks, which revolutionized the way developers manage state and... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-hooks-useeffect-usestate-and-usecontext/</link>
                <guid isPermaLink="false">66c4c41226a77d9936ef0a4d</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ react hooks ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joan Ayebola ]]>
                </dc:creator>
                <pubDate>Mon, 04 Dec 2023 18:38:16 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/11/Orange-and-Yellow-Retro-Flower-Power-Daily-Class-Agenda-Template.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>React is a powerful JavaScript library for building user interfaces. And it has undergone significant changes over the years. </p>
<p>One of the most noteworthy additions is the introduction of hooks, which revolutionized the way developers manage state and side effects in functional components. </p>
<p>In this guide, we'll explore three fundamental hooks for beginners: <code>useState</code>, <code>useEffect</code>, and <code>useContext</code>.</p>
<h2 id="heading-introduction-to-react-hooks">Introduction to React Hooks</h2>
<p>Before hooks, stateful logic in React was primarily managed using class components. </p>
<p>With the advent of functional components and hooks, developers gained a more concise and expressive way to handle state and lifecycle methods. Hooks allow you to use state and other React features without writing a class.</p>
<h3 id="heading-what-are-react-hooks">What are React Hooks?</h3>
<p>React hooks are functions that enable functional components to use state and lifecycle features that were previously only available in class components. They were introduced in React 16.8 to provide a more consistent way to manage stateful logic in functional components.</p>
<h2 id="heading-how-to-use-the-usestate-hook">How to Use the <code>useState</code> Hook</h2>
<p>The <code>useState</code> hook is perhaps the most basic and essential hook in React. It enables you to add state to your functional components, allowing them to keep track of data that changes over time. Let's dive into how <code>useState</code> works with a simple example.</p>
<h3 id="heading-basic-usage-of-usestate">Basic Usage of <code>useState</code></h3>
<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> Counter = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// Declare a state variable named 'count' with an initial value of 0</span>
  <span class="hljs-keyword">const</span> [count, setCount] = useState(<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>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Count: {count}<span class="hljs-tag">&lt;/<span class="hljs-name">p</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> setCount(count + 1)}&gt;Increment<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> Counter;
</code></pre>
<p>In this example, we import the <code>useState</code> hook from the 'react' library. The <code>useState</code> function returns an array with two elements: the current state value (<code>count</code>) and a function (<code>setCount</code>) to update it. We initialize <code>count</code> to 0, and clicking the "Increment" button increases its value.</p>
<h3 id="heading-how-to-use-multiple-usestate-hooks">How to Use Multiple <code>useState</code> Hooks</h3>
<p>You can use the <code>useState</code> hook multiple times in a single component to manage different pieces of state independently. Let's modify our <code>Counter</code> component to include a second piece of state.</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> Counter = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);
  <span class="hljs-keyword">const</span> [isEven, setIsEven] = useState(<span class="hljs-literal">false</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>Count: {count}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{isEven ? 'Even' : 'Odd'}<span class="hljs-tag">&lt;/<span class="hljs-name">p</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> setCount(count + 1)}&gt;Increment<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setIsEven(!isEven)}&gt;Toggle Even/Odd<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> Counter;
</code></pre>
<p>Now, our <code>Counter</code> component has two independent pieces of state: <code>count</code> and <code>isEven</code>. Clicking the "Toggle Even/Odd" button will switch the value of <code>isEven</code>.</p>
<h2 id="heading-how-to-use-the-useeffect-hook">How to Use the <code>useEffect</code> Hook</h2>
<p>The <code>useEffect</code> hook is used to perform side effects in your functional components, such as fetching data, subscribing to external events, or manually changing the DOM. It combines the functionality of <code>componentDidMount</code>, <code>componentDidUpdate</code>, and <code>componentWillUnmount</code> in class components.</p>
<h3 id="heading-basic-usage-of-useeffect">Basic Usage of <code>useEffect</code></h3>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> DataFetcher = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [data, setData] = useState(<span class="hljs-literal">null</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-comment">// Fetch data from an API</span>
    fetch(<span class="hljs-string">'https://api.example.com/data'</span>)
      .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> response.json())
      .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> setData(result))
      .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error fetching data:'</span>, error));
  }, []); <span class="hljs-comment">// Empty dependency array means this effect runs once after the initial render</span>

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      {data ? (
        <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
          {data.map((item) =&gt; (
            <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{item.id}</span>&gt;</span>{item.name}<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">p</span>&gt;</span>Loading data...<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">export</span> <span class="hljs-keyword">default</span> DataFetcher;
</code></pre>
<p>In this example, the <code>useEffect</code> hook is used to fetch data from an API when the component mounts. The second argument of <code>useEffect</code> is an array of dependencies. If the dependencies change between renders, the effect will run again. An empty array means the effect runs once after the initial render.</p>
<h3 id="heading-cleaning-up-in-useeffect">Cleaning Up in <code>useEffect</code></h3>
<p>Sometimes, side effects need to be cleaned up, especially when dealing with subscriptions or timers to prevent memory leaks. The <code>useEffect</code> hook can return a cleanup function that will be executed when the component unmounts.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> Timer = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [seconds, setSeconds] = useState(<span class="hljs-number">0</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> intervalId = <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =&gt;</span> {
      setSeconds(<span class="hljs-function">(<span class="hljs-params">prevSeconds</span>) =&gt;</span> prevSeconds + <span class="hljs-number">1</span>);
    }, <span class="hljs-number">1000</span>);

    <span class="hljs-comment">// Cleanup function to clear the interval when the component unmounts</span>
    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">clearInterval</span>(intervalId);
  }, []); <span class="hljs-comment">// Empty dependency array for initial setup only</span>

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Seconds: {seconds}<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> Timer;
</code></pre>
<p>In this example, the <code>setInterval</code> function is used to update the <code>seconds</code> state every second. The cleanup function returned by <code>useEffect</code> clears the interval when the component is unmounted.</p>
<h2 id="heading-how-to-use-the-usecontext-hook">How to Use the <code>useContext</code> Hook</h2>
<p>The <code>useContext</code> hook is used to consume values from a React context. Context provides a way to pass data through the component tree without having to pass props manually at every level. Let's explore how <code>useContext</code> works with a simple example.</p>
<h3 id="heading-how-to-create-a-context">How to Create a Context</h3>
<p>First, let's create a context to hold a user's authentication status.</p>
<pre><code class="lang-jsx"><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> AuthContext = createContext();

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> AuthProvider = <span class="hljs-function">(<span class="hljs-params">{ children }</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> [isAuthenticated, setIsAuthenticated] = useState(<span class="hljs-literal">false</span>);

  <span class="hljs-keyword">const</span> login = <span class="hljs-function">() =&gt;</span> {
    setIsAuthenticated(<span class="hljs-literal">true</span>);
  };

  <span class="hljs-keyword">const</span> logout = <span class="hljs-function">() =&gt;</span> {
    setIsAuthenticated(<span class="hljs-literal">false</span>);
  };

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

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> useAuth = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> useContext(AuthContext);
};
</code></pre>
<p>In this example, we create an <code>AuthContext</code> using <code>createContext</code> and provide an <code>AuthProvider</code> component. The <code>AuthProvider</code> component wraps its children with the context provider and includes functions for logging in and out.</p>
<h3 id="heading-how-to-use-usecontext">How to Use <code>useContext</code></h3>
<p>Now, let's use the <code>useContext</code> hook in a component to access the authentication status.</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> { useAuth } <span class="hljs-keyword">from</span> <span class="hljs-string">'./AuthContext'</span>;

<span class="hljs-keyword">const</span> AuthStatus = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> { isAuthenticated, login, logout } = useAuth();

  <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>User is {isAuthenticated ? 'logged in' : 'logged out'}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{login}</span>&gt;</span>Login<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>


      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{logout}</span>&gt;</span>Logout<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> AuthStatus;
</code></pre>
<p>Here, the <code>useAuth</code> hook is used to access the values provided by the <code>AuthContext</code>. The <code>AuthStatus</code> component displays the user's login status and provides buttons to log in and out.</p>
<h2 id="heading-putting-it-all-together">Putting It All Together</h2>
<p>Let's create a more complex example that combines <code>useState</code>, <code>useEffect</code>, and <code>useContext</code> in a single component. Suppose we have a component that fetches user data from an API and displays it, taking into account the user's authentication status.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { useAuth } <span class="hljs-keyword">from</span> <span class="hljs-string">'./AuthContext'</span>;

<span class="hljs-keyword">const</span> UserProfile = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> { isAuthenticated } = useAuth();
  <span class="hljs-keyword">const</span> [userData, setUserData] = useState(<span class="hljs-literal">null</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">if</span> (isAuthenticated) {
      <span class="hljs-comment">// Fetch user data when authenticated</span>
      fetch(<span class="hljs-string">'https://api.example.com/user'</span>)
        .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> response.json())
        .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> setUserData(result))
        .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error fetching user data:'</span>, error));
    }
  }, [isAuthenticated]); <span class="hljs-comment">// Run the effect when isAuthenticated changes</span>

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      {isAuthenticated ? (
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Welcome, {userData ? userData.name : 'User'}!<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>Email: {userData ? userData.email : 'Loading...'}<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 class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Please log in to view your profile.<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">export</span> <span class="hljs-keyword">default</span> UserProfile;
</code></pre>
<p>In this example, the <code>UserProfile</code> component uses the <code>useAuth</code> hook to check the user's authentication status. If authenticated, it fetches the user data and displays a personalized welcome message. If not authenticated, it prompts the user to log in.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>React hooks, including <code>useState</code>, <code>useEffect</code>, and <code>useContext</code>, have transformed the way developers write components by providing a more intuitive and flexible approach to managing state and side effects. </p>
<p>As you continue your journey with React, mastering these hooks will empower you to build more efficient and maintainable applications.</p>
<p>Remember, practice is key to becoming proficient with React hooks. Experiment with different scenarios, explore additional hooks like <code>useReducer</code> and <code>useCallback</code>, and stay up-to-date with the React documentation for any new features or best practices. Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ React Lifecycle Methods and Hooks – a Beginner's Guide ]]>
                </title>
                <description>
                    <![CDATA[ React is all about building user interfaces. And to do that effectively, React provides ways for components to manage their lifecycles. This means that components can perform specific tasks at different stages of their existence, from the moment they... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-lifecycle-methods-and-hooks-for-beginners/</link>
                <guid isPermaLink="false">66d45e08680e33282da25e59</guid>
                
                    <category>
                        <![CDATA[ hooks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ lifecycle methods ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ react hooks ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Casmir Onyekani ]]>
                </dc:creator>
                <pubDate>Mon, 02 Oct 2023 17:22:49 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/10/lifecycle.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p><a target="_blank" href="https://www.freecodecamp.org/news/react-beginner-handbook/#howmuchjavascriptyouneedtoknowtousereact">React</a> is all about building user interfaces. And to do that effectively, React provides ways for components to manage their lifecycles.</p>
<p>This means that components can perform specific tasks at different stages of their existence, from the moment they are created to the point they are removed from the user interface.</p>
<p>Lifecycle methods have been a fundamental part of React for many years. But with the introduction of hooks, React's approach to managing state and side effects in functional components has become more intuitive and flexible.</p>
<p>Just a quick note: although hooks generally replace class components, there are no plans to remove classes from React.</p>
<h3 id="heading-why-this-guide">Why This Guide?</h3>
<p>In this tutorial, you will learn about class component lifecycle methods such as <code>componentDidMount</code>, <code>componentDidUpdate</code>, <code>componentWillUnmount</code>, and <code>shouldComponentUpdate</code>.</p>
<p>You'll also explore React hooks like <code>useState</code>, <code>useEffect</code>, and <code>useContext</code>, and understand why they were introduced. This will make your React journey smoother and more enjoyable.</p>
<p>Whether you're just getting started with React or looking to deepen your understanding, this guide will equip you with the knowledge you need to build responsive and interactive web applications using React's powerful tools.</p>
<p>Let's dive in and uncover the magic of React lifecycle methods and hooks.</p>
<h2 id="heading-how-the-component-lifecycle-works">How the Component Lifecycle Works</h2>
<p>In React, components go through a lifecycle composed of distinct stages. Each of these stages offers specific methods that you can customize to run code at various moments during a component's existence.</p>
<p>These methods help you perform tasks such as initializing data, managing updates, and tidying up resources as needed.</p>
<h3 id="heading-class-component-lifecycle-methods">Class Component Lifecycle Methods</h3>
<p>Let's start by looking at the class component lifecycle methods. These were the primary way to manage component lifecycle before the introduction of hooks.</p>
<h4 id="heading-how-to-use-componentdidmount">How to use <code>componentDidMount</code>:</h4>
<p>This is called after a component has been inserted into the DOM. It's a great place to perform initial setup tasks, like fetching data from an API or setting up event listeners.</p>
<p>Code example:</p>
<pre><code class="lang-jsx">
<span class="hljs-keyword">import</span> React, { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyComponent</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-built_in">super</span>();
    <span class="hljs-built_in">this</span>.state = {
      <span class="hljs-attr">data</span>: <span class="hljs-literal">null</span>,
    };
  }

  componentDidMount() {
    <span class="hljs-comment">// This is where you can perform initial setup.</span>

    <span class="hljs-comment">// In this example, we simulate fetching data from an API after the             component has mounted.</span>
    <span class="hljs-comment">// We use a setTimeout to mimic an asynchronous operation.</span>
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-keyword">const</span> fetchedData = <span class="hljs-string">'This data was fetched after mounting.'</span>;
      <span class="hljs-built_in">this</span>.setState({ <span class="hljs-attr">data</span>: fetchedData });
    }, <span class="hljs-number">2000</span>); <span class="hljs-comment">// Simulate a 2-second delay</span>
  }

  render() {
    <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>componentDidMount Example<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        {this.state.data ? (
          <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Data: {this.state.data}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        ) : (
          <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Loading data...<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">export</span> <span class="hljs-keyword">default</span> MyComponent;
</code></pre>
<p>In this example, we created a class component called <code>MyComponent</code>. In the constructor, the component's state is initialized with data set to null, and we use it to store the fetched data.</p>
<p>In the <code>componentDidMount</code> method, we simulate fetching data from an API using <code>setTimeout</code> to mimic an asynchronous operation. After 2 seconds (2000 milliseconds), the component's state updates with the fetched data.</p>
<p>In the render method, content is conditionally rendered based on the data state. If data is null, a <code>Loading data...</code> message is displayed. Otherwise, the fetched data is displayed.</p>
<p>When you use this component in your application, you'll notice that the Loading data... message is shown initially, and after 2 seconds, the fetched data is displayed. This demonstrates how <code>componentDidMount</code> is useful for performing tasks after a component has been added to the DOM.</p>
<h4 id="heading-how-to-use-componentdidupdateb">How to use <code>componentDidUpdate</code>B:</h4>
<p>This is called after a component has re-rendered due to changes in its state or props. It's a great place to handle side effects or perform additional actions based on those changes.</p>
<p>Code Example:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Counter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-built_in">super</span>();
    <span class="hljs-built_in">this</span>.state = {
      <span class="hljs-attr">count</span>: <span class="hljs-number">0</span>,
    };
  }

  <span class="hljs-comment">// This method will be called when the "Increment" button is clicked</span>
  handleIncrement = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">this</span>.setState({ <span class="hljs-attr">count</span>: <span class="hljs-built_in">this</span>.state.count + <span class="hljs-number">1</span> });
  };

  <span class="hljs-comment">// componentDidUpdate is called after the component updates</span>
  componentDidUpdate(prevProps, prevState) {
    <span class="hljs-comment">// You can access the previous props and state here</span>
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Component updated'</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Previous state:'</span>, prevState);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Current state:'</span>, <span class="hljs-built_in">this</span>.state);
  }

  render() {
    <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>Counter<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Count: {this.state.count}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{this.handleIncrement}</span>&gt;</span>Increment<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> Counter;
</code></pre>
<p>In this code example, we create a <code>Counter</code> class component with a constructor that initializes the <code>count</code> state to 0. The <code>handleIncrement</code> method updates the count state when the <em>Increment</em> button is clicked.</p>
<p>Inside the <code>componentDidUpdate</code> lifecycle method, we log a message (Component updated) to the console. We also log both the previous state (prevState) and the current state (this.state). This demonstrates how you can access both the previous and current values during an update. The render method displays the current count and a button to increment it.</p>
<p>Now, when you use this <code>Counter</code> component in your application, open the browser's console. Every time you click the <em>Increment</em> button, you'll see messages in the console indicating that the component has updated, along with the previous and current state values.</p>
<p>You can use <code>componentDidUpdate</code> for various purposes, such as making network requests when props or state change, updating the DOM based on state changes, or interacting with third-party libraries after an update. It provides a way to perform actions that should occur specifically after a component has re-rendered.</p>
<h4 id="heading-how-to-use-componentwillunmount">How to use <code>componentWillUnmount</code></h4>
<p>This is called just before a component is removed from the DOM. It's a crucial place to perform cleanup tasks, such as clearing timers, unsubscribing from events, or releasing resources to prevent [memory leaks](https://en.wikipedia.org/wiki/Memory_leak#:~:text=In computer science%2C a memory,longer needed is not released.).</p>
<p>Let's illustrate a simple React component that sets up a timer when it mounts, using <code>componentDidMount</code> method, and clears that timer when it unmounts using the <code>componentWillUnmount</code> method.</p>
<p>Code example:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TimerComponent</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-built_in">super</span>();
    <span class="hljs-built_in">this</span>.state = {
      <span class="hljs-attr">seconds</span>: <span class="hljs-number">0</span>,
    };
    <span class="hljs-built_in">this</span>.timer = <span class="hljs-literal">null</span>; <span class="hljs-comment">// Initialize the timer</span>
  }

  <span class="hljs-comment">// When the component mounts, start the timer</span>
  componentDidMount() {
    <span class="hljs-built_in">this</span>.timer = <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-built_in">this</span>.setState({ <span class="hljs-attr">seconds</span>: <span class="hljs-built_in">this</span>.state.seconds + <span class="hljs-number">1</span> });
    }, <span class="hljs-number">1000</span>); <span class="hljs-comment">// Update every 1 second (1000 milliseconds)</span>
  }

  <span class="hljs-comment">// When the component unmounts, clear the timer to prevent memory leaks</span>
  componentWillUnmount() {
    <span class="hljs-built_in">clearInterval</span>(<span class="hljs-built_in">this</span>.timer);
  }

  render() {
    <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>Timer Component<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Elapsed Time: {this.state.seconds} seconds<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">export</span> <span class="hljs-keyword">default</span> TimerComponent;
</code></pre>
<p>In this example, we created the <code>TimerComponent</code> class. Inside the constructor, the component's state is initialized with a seconds property, which we'll use to keep track of the elapsed time. The timer variable is also set to null.</p>
<p>In the <code>componentDidMount</code> lifecycle method, the timer is started by using <code>setInterval</code>. This timer increments the seconds state property every second.</p>
<p>In the <code>componentWillUnmount</code> lifecycle method, the timer is cleared using <code>clearInterval</code> to ensure that it doesn't continue running after the component has been removed from the DOM.</p>
<p>In the render method, the elapsed time is displayed based on the seconds state property.</p>
<p>When you use this <code>TimerComponent</code> in your application and render it, you'll notice that the timer starts when the component is mounted and stops when the component is unmounted. This is thanks to the cleanup performed in the <code>componentWillUnmount</code> method. This prevents resource leaks and ensures that<br>the timer is properly managed throughout the component's lifecycle.</p>
<h4 id="heading-how-to-use-shouldcomponentupdate">How to use <code>shouldComponentUpdate</code></h4>
<p>We use this lifecycle method to control whether a component should re-render when its state or props change. It is particularly useful for optimizing performance by preventing unnecessary renders.</p>
<p>Let's create a simple React class component and use the <code>shouldComponentUpdate</code> method to decide whether the component should re-render based on changes in its state.</p>
<p>Code Example:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Counter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-built_in">super</span>();
    <span class="hljs-built_in">this</span>.state = {
      <span class="hljs-attr">count</span>: <span class="hljs-number">0</span>,
    };
  }

  shouldComponentUpdate(nextProps, nextState) {
    <span class="hljs-comment">// Allow the component to re-render only if the count is even</span>
    <span class="hljs-keyword">if</span> (nextState.count % <span class="hljs-number">2</span> === <span class="hljs-number">0</span>) {
      <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>; <span class="hljs-comment">// Re-render</span>
    }
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>; <span class="hljs-comment">// Don't re-render</span>
  }

  incrementCount = <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-attr">count</span>: prevState.count + <span class="hljs-number">1</span> }));
  };

  render() {
    <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>Counter Example<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Count: {this.state.count}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{this.incrementCount}</span>&gt;</span>Increment<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> Counter;
</code></pre>
<p>In this example, we created the <code>Counter</code> class component that maintains a count state, which starts at 0. In the <code>shouldComponentUpdate</code> method, we check whether the next state's count is even. If it is, we allow the component to re-render. Otherwise, we prevent the re-render.</p>
<p>The <code>incrementCount</code> method is called when the <em>Increment</em> button is clicked. It updates the count state by incrementing it.</p>
<p>In the render method, the current count and a button to increment it is displayed.</p>
<p>If you click the <em>Increment</em> button and the count becomes an odd number, the component won't re-render. This behavior demonstrates how <code>shouldComponentUpdate</code> can be used to optimize rendering in situations where not all state changes should trigger a re-render.</p>
<h2 id="heading-introducing-react-hooks">Introducing React Hooks</h2>
<p>React introduced hooks in version 16.8. They granted functional components access to state and various React features without writing class components.</p>
<p>As a result, class components have become largely unnecessary. Hooks simplify component logic and make it more reusable.</p>
<h3 id="heading-why-use-hooks">Why use Hooks?</h3>
<p>Hooks were introduced to address several issues and make React code easier to understand and maintain:</p>
<ul>
<li><p>Complexity – class components can become complex when managing state and side effects.</p>
</li>
<li><p>Reusability – logic in class components isn't easily shareable between components.</p>
</li>
<li><p>Learning Curve – class components introduce a steeper learning curve for newcomers to React.</p>
</li>
</ul>
<h3 id="heading-commonly-used-react-hooks">Commonly used React Hooks</h3>
<h4 id="heading-the-usestate-hook">The <code>useState</code> hook</h4>
<p><code>useState</code> lets you add state to functional components. It returns an array with the current state value and a function to update it.</p>
<p>Code Example:</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-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Counter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [count, setCount] = useState(<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>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Count: {count}<span class="hljs-tag">&lt;/<span class="hljs-name">p</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> setCount(count + 1)}&gt;Increment<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>
  );
}
</code></pre>
<p>In this example, we used the <code>useState</code> hook to manage a counter's state. When the Increment button is clicked, <code>setCount</code> updates the count state, causing the component to re-render with the updated value.</p>
<h4 id="heading-the-useeffect-hook">The <code>useEffect</code> hook</h4>
<p><code>useEffect</code> is used for side effects in functional components, similar to <code>componentDidMount</code> and <code>componentDidUpdate</code>. It runs after rendering and can be controlled by specifying dependencies.</p>
<p>Code Example:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Example</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [data, setData] = useState(<span class="hljs-literal">null</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-comment">// Fetch data from an API</span>
    fetch(<span class="hljs-string">'https://api.example.com/data'</span>)
      .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
      .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> setData(data));
  }, []); <span class="hljs-comment">// Empty dependency array, runs only once</span>

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>{data ? data.message : 'Loading...'}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
}
</code></pre>
<p>In this example, <code>useEffect</code> is used to fetch data from an API when the component mounts. The empty dependency array <code>[]</code> ensures that the effect runs only once.<br>When the data is fetched, <code>setData</code> updates the data state, causing a re-render with the fetched information.</p>
<h4 id="heading-the-usecontext-hook">The <code>useContext</code> hook</h4>
<p><code>useContext</code> allows functional components to access context values. It's a way to pass data down the component tree without explicitly passing props.</p>
<p>Code Example:</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-comment">// Create a context</span>
<span class="hljs-keyword">const</span> MyContext = React.createContext();

<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> value = useContext(MyContext);

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Context Value: {value}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
}
</code></pre>
<p>In this example, we create a context called <code>MyContext</code>. The <code>useContext</code> hook allows <code>MyComponent</code> to access the value stored in this context. It's a powerful tool for managing global state in your application.</p>
<h3 id="heading-benefits-of-custom-hooks">Benefits of custom hooks</h3>
<p>Custom hooks are functions that use hooks internally and can be reused across multiple components. They help encapsulate and share complex logic.</p>
<p>Here's an example of a custom hook called <code>useLocalStorage</code> that simplifies storing and retrieving data in the browser's local storage:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useLocalStorage</span>(<span class="hljs-params">key, initialValue</span>) </span>{
  <span class="hljs-comment">// Retrieve the stored value from local storage</span>
  <span class="hljs-keyword">const</span> storedValue = <span class="hljs-built_in">localStorage</span>.getItem(key);

  <span class="hljs-comment">// Initialize the state with the stored value or the initial value</span>
  <span class="hljs-keyword">const</span> [value, setValue] = useState(storedValue || initialValue);

  <span class="hljs-comment">// Update the local storage whenever the state changes</span>
  <span class="hljs-keyword">const</span> setStoredValue = <span class="hljs-function">(<span class="hljs-params">newValue</span>) =&gt;</span> {
    setValue(newValue);
    <span class="hljs-built_in">localStorage</span>.setItem(key, newValue);
  };

  <span class="hljs-keyword">return</span> [value, setStoredValue];
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> useLocalStorage;
</code></pre>
<p>In this custom hook, we import <code>useState</code> from React because we'll use it to manage the state. The <code>useLocalStorage</code> function takes two parameters:</p>
<ul>
<li><p><strong>key</strong>: A string representing the key under which the data will be stored in local storage.</p>
</li>
<li><p><code>**initialValue**</code>: The initial value for the state.</p>
</li>
</ul>
<p>Inside the hook, we first attempted to retrieve the stored value from local storage using <code>localStorage.getItem(key)</code>. Then we initialized the state variable value using <code>useState</code>, using the <code>storedValue</code> if it exists or the <code>initialValue</code> if not.</p>
<p>Next, we defined a function <code>setStoredValue</code> that updates both the state and the local storage when called. It sets the new value in local storage using <code>localStorage.setItem(key, newValue)</code>.</p>
<p>Finally, we returned an array <code>[value, setStoredValue]</code> as the hook's return value, allowing components to access the stored value and update it as needed.</p>
<p>Here's an example of how you can use the <code>useLocalStorage</code> hook in a component:</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> useLocalStorage <span class="hljs-keyword">from</span> <span class="hljs-string">'./useLocalStorage'</span>; <span class="hljs-comment">// Import the custom hook</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-comment">// Use the custom hook to manage a "username" stored in local storage</span>
  <span class="hljs-keyword">const</span> [username, setUsername] = useLocalStorage(<span class="hljs-string">'username'</span>, <span class="hljs-string">'Guest'</span>);

  <span class="hljs-keyword">const</span> handleInputChange = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    setUsername(e.target.value);
  };

  <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>Hello, {username}!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
        <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
        <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Enter your username"</span>
        <span class="hljs-attr">value</span>=<span class="hljs-string">{username}</span>
        <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleInputChange}</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 import the <code>useLocalStorage</code> custom hook and use it to manage a username value in local storage. The component initializes the username state using the hook and updates it when the input field changes.</p>
<p>The value is stored and retrieved from local storage, allowing it to persist across page reloads.</p>
<p>Custom hooks are a powerful way to encapsulate and reuse complex logic in React applications, making your code more modular and maintainable.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>React provides developers with powerful tools to manage the lifecycles of their components. These lifecycles allow components to perform specific tasks at different stages of their existence, from creation to removal.</p>
<p>In this guide, we've explored React's class component lifecycle methods. These methods have been a fundamental part of React for many years and continue to be relevant in certain scenarios.</p>
<p>You've also been introduced to React Hooks. These have become the preferred way to manage state and side effects in React applications. They offer a more intuitive and flexible approach to building components.</p>
<p>While hooks have gained popularity and generally replace the need for class components, it's important to note that there are no plans to remove class components from React. Existing codebases and third-party libraries may still use class components, so understanding both class component lifecycles and hooks is<br>valuable for React developers.</p>
<p>In summary, React's lifecycle methods and hooks are crucial for building dynamic and efficient applications, and they offer developers a range of options to manage component behavior and state. As you continue to explore and work with React,<br>you'll find that having a solid understanding of both lifecycles and hooks will make you a more versatile and capable React developer.</p>
<p>If you found this guide helpful and enjoyable, please give it a like. For more insightful tutorials, follow me on <a target="_blank" href="https://twitter.com/casweb_dev">X</a> for updates 🙏.</p>
<p>Enjoy your coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Caching in React – How to Use the useMemo and useCallback Hooks ]]>
                </title>
                <description>
                    <![CDATA[ By Scott Gary As you become more proficient at coding in React, performance will become a major focal point in your development process.  As with any tool or programming methodology, caching plays a huge role when it comes to optimizing React applica... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/caching-in-react/</link>
                <guid isPermaLink="false">66d460eea326133d12440a76</guid>
                
                    <category>
                        <![CDATA[ caching ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ react hooks ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 15 May 2023 18:39:25 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/caching-react.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Scott Gary</p>
<p>As you become more proficient at coding in React, performance will become a major focal point in your development process. </p>
<p>As with any tool or programming methodology, caching plays a huge role when it comes to optimizing React applications.</p>
<p>Caching in React typically goes by the term <em>memoization</em>. It's used to improve performance by reducing the amount of times a component renders due to state or prop mutations.</p>
<p>React provides two APIs for caching: useMemo and useCallback. useCallback is a hook that memoizes a function, while useMemo is a hook that memoizes a value. These two hooks are often used in conjunction with the Context API to further improve efficiency.</p>
<p>Here’s a basic list of topics we’ll be covering in this article:</p>
<ol>
<li>React caching default behavior.</li>
<li>The useMemo hook.</li>
<li>The useCallback hook.</li>
</ol>
<p>In order to follow along, you'll need a decent understanding of React and stateful components.</p>
<h2 id="heading-default-caching-behavior-in-react">Default Caching Behavior in React</h2>
<p>By default, <a target="_blank" href="https://www.ohmycrawl.com/react/">React</a> uses a technique called “shallow comparison” to determine whether a component should be re-rendered. This basically means that if the props or state of a component haven’t changed, React will assume that the output of the component hasn’t changed either and won’t re-render it.</p>
<p>While this default caching behavior is very effective by itself, it isn’t always enough to optimize complex components that require advanced state management. </p>
<p>In order to achieve more control over your component’s caching and rendering behavior, React offers the <strong>useMemo</strong> and <strong>useCallback</strong> hooks.</p>
<h2 id="heading-caching-in-react-with-the-usememo-hook">Caching in React with the useMemo Hook</h2>
<p>useMemo is useful when you need to do an expensive computation to retrieve a value, and you want to ensure that the computation is only performed when necessary. By memoizing the value using useMemo, you can ensure that the value is only computed when its dependencies change.</p>
<p>In a React component, you may have multiple properties that make up your state. If a piece of state changes that has nothing to do with our expensive value, why recompute it if it hasn’t changed?</p>
<p>Here’s an example code block reflecting a basic useMemo implementation:</p>
<pre><code>react
<span class="hljs-keyword">import</span> React, { useState, useMemo } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Example</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> [txt, setTxt] = useState(“Some text”);
<span class="hljs-keyword">const</span> [a, setA] = useState(<span class="hljs-number">0</span>);
<span class="hljs-keyword">const</span> [b, setB] = useState(<span class="hljs-number">0</span>);
<span class="hljs-keyword">const</span> sum = useMemo(<span class="hljs-function">() =&gt;</span> {
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Computing sum...'</span>);
<span class="hljs-keyword">return</span> a + b;
}, [a, b]);
<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>Text: {txt}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>a: {a}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>b: {b}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>sum: {sum}<span class="hljs-tag">&lt;/<span class="hljs-name">p</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> setTxt(“New Text!”)}&gt;Set Text<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setA(a + 1)}&gt;Increment a<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setB(b + 1)}&gt;Increment b<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>
);
}
</code></pre><p>In our Example component above, assume the <strong>sum()</strong> function performs an expensive computation. If the <strong>txt</strong> state is updated, React is going to re-render our component, but because we memoized the returned value of sum, this function will not run again at this time.</p>
<p>The only time the <strong>sum()</strong> function will run is if either the <strong>a</strong> or <strong>b</strong> state has been mutated (changed). This is an excellent improvement upon the default behavior, which will rerun this method upon each re-render.</p>
<h2 id="heading-caching-in-react-with-the-usecallback-hook">Caching in React with the useCallback Hook</h2>
<p>useCallback is useful when you need to pass a function as a prop to a child component, and you want to ensure that the function reference does not change unnecessarily. By memoizing the function using useCallback, you can ensure that the function reference remains the same as long as its dependencies do not change.</p>
<p>Without getting too heavy into JavaScript function references, let’s just take a look at how they can affect the rendering of your React app. When a function reference changes, any child components that receive the function as a prop will re-render, even if the function logic itself has not changed.</p>
<p>This is because, as we already mentioned, React does a shallow comparison of prop values to determine whether a component should re-render, and a new function reference will always be considered a different value than the previous one.</p>
<p>In other words, the simple act of redeclaring a function (even the same exact function), causes the reference to change, and will cause the child component that receives the function as a prop to unnecessarily re-render.</p>
<p>Here’s an example code block reflecting a basic useCallback implementation:</p>
<pre><code>react
<span class="hljs-keyword">import</span> React, { useState, useCallback } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ChildComponent</span>(<span class="hljs-params">{ onClick }</span>) </span>{
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'ChildComponent is rendered'</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">onClick</span>=<span class="hljs-string">{onClick}</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Example</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);
<span class="hljs-keyword">const</span> [txt, setTxt] = useState(“Some text…”);
<span class="hljs-keyword">const</span> incrementCount = useCallback(<span class="hljs-function">() =&gt;</span> {
setCount(<span class="hljs-function"><span class="hljs-params">prevCount</span> =&gt;</span> prevCount + <span class="hljs-number">1</span>);
}, [setCount]);
<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>Text: {txt}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Count: {count}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{setTxt}</span>&gt;</span>Set Text<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{setCount}</span>&gt;</span>Increment<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">ChildComponent</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{incrementCount}</span> /&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
);
}
</code></pre><p>As you can see in the above example, we pass the <strong>incrementCount</strong> method instead of the <strong>setCount</strong> method to the child component. This is because <strong>incrementCount</strong> is memoized, and when we run our <strong>setTxt</strong> method, it won’t cause the child component to unnecessarily re-render.</p>
<p>The only way our child component will re-render in this example is if the <strong>setCount</strong> method runs, because we passed it as a dependency parameter to our <strong>useCallback</strong> memoization.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Caching is an important technique for optimizing React applications. By reducing unnecessary re-renders, caching can help to improve the performance and efficiency of your application.</p>
<p>React provides a default caching behavior by using a virtual DOM to compare changes in state and props, and only updating components after a shallow comparison reflects changes. This is a great optimization technique that’s sufficient in many scenarios, but sometimes more fine-grained control is desired.</p>
<p>The useMemo and useCallback hooks were created to achieve this fine-grained control. </p>
<p>useMemo is used to memoize the <em>results</em> of a function call, and is useful when the function is expensive to compute and the result does not change often. </p>
<p>useCallback is used to memoize the actual reference of a function rather than the returned value, and is used when the function is passed as a prop to child components that might cause unnecessary re-renders.</p>
<p>Want to learn more? To learn more check out the <a target="_blank" href="https://www.ohmycrawl.com/blog/">OhMyCrawl Blog</a> for more programming tips for SEO.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use the useState() Hook in React – Explained with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ By Mwendwa Bundi Emma One of the most well-known React hooks is the useState() hook. It lets you add a state variable to your component. The useState() hook can conveniently hold strings, arrays, numbers, objects and much more. In this article, we ar... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/usestate-hook-3-different-examples/</link>
                <guid isPermaLink="false">66d46044264384a65d5a95a2</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ react hooks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 08 May 2023 14:11:06 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/usestate---hook-2.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Mwendwa Bundi Emma</p>
<p>One of the most well-known React hooks is the <code>useState()</code> hook. It lets you add a state variable to your component. The <code>useState()</code> hook can conveniently hold strings, arrays, numbers, objects and much more.</p>
<p>In this article, we are going to learn about the <code>useState()</code> hook and demonstrate its use with three different examples: a button with conditional rendering, form handling, and the famous counter.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<ul>
<li>You'll need basic knowledge of HTML, CSS and JavaScript to understand the ideas behind what you are creating in this tutorial. </li>
<li>It's also helpful to have beginner's knowledge of React.</li>
<li>Finally, you'll need an IDE, preferably <a target="_blank" href="https://code.visualstudio.com/">VS Code</a>.</li>
</ul>
<p>Once you have your React application up and running, you are ready to use useState. To get started, you need to import <code>useState()</code> from React as shown below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { UseState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
</code></pre>
<h2 id="heading-how-does-usestate-work">How Does <code>useState()</code> Work?</h2>
<p>The <code>useState()</code> hook works by handling and managing state in your applications. </p>
<p>The <code>useState()</code> hook takes the first (initial) value of the state variable as its argument. The second value then sets your state, which is why it's always initiated as <code>setState</code>. So how does this work?</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> [state, setState] = useState(initial values goes here)

<span class="hljs-keyword">const</span> [calories, setCalories] = useState(initial value <span class="hljs-keyword">of</span> calories)
</code></pre>
<p>In the case of the first render, it returns the initial state and updates to a different value during the re-render using the <code>set</code> function.</p>
<h2 id="heading-conditional-rendering-with-the-usestate-hook">Conditional Rendering with the <code>useState()</code> Hook</h2>
<p>This example allows you to update state depending on two conditions: if the user is logged in or not. This also explains why the initial state is set to false, to mean the user is not logged in.</p>
<p>You are going to create a login button that uses the <code>useState()</code> hook to render two different outcomes. </p>
<p>One is a sign-in button with a message asking the user to sign in. The other is a button that, once the user is signed in, gives them the choice to sign out.</p>
<pre><code class="lang-react">import React from 'react'

const Signin = () =&gt; {
  return (
    &lt;div&gt;
        &lt;div&gt;
            &lt;button type="button"&gt;Sign Out&lt;/button&gt;
            &lt;p&gt;Welcome back, good to see you in here&lt;p&gt;
        &lt;/div&gt;
        &lt;div&gt;
            &lt;button type="button"&gt;Sign In&lt;/button&gt;
            &lt;p&gt;Please Sign in&lt;/p&gt;
        &lt;/div&gt;
    &lt;/div&gt;
  )
}

export default Signin;
</code></pre>
<p>To implement the sign in and sign out functionalities, you will have to import <code>useState()</code>. Then you'll need to use conditional rendering to specify how the buttons will respond to a click.</p>
<pre><code class="lang-react">import React, { useState } from 'react'

const Signin = () =&gt; {
    const [signedin, setSignedin] = useState(false)

    const handleSignin = () =&gt; {
        setSignedin(true)
    }

    const handleSignout = () =&gt; {
        setSignedin(false)
    }
  return (
         &lt;div&gt;
           { signedin ? ( 
        &lt;div&gt;
            &lt;button type="button" onClick={handleSignout}&gt;Sign Out&lt;/button&gt;
            &lt;p&gt;Welcome back, good to see you in here&lt;/p&gt;
        &lt;/div&gt;) :

        (&lt;div&gt;
            &lt;button type="button"onClick={handleSignin}&gt;Sign In&lt;/button&gt;
            &lt;p&gt;Please Sign in&lt;/p&gt;
        &lt;/div&gt;)
           }
        &lt;/div&gt;
  )
}

export default Signin;
</code></pre>
<p>What's happening in the code above?</p>
<p>First, you created a variable with the <code>useState()</code> hook that sets <code>signedin</code> to false. Why? Because on the first load, you don't want the user to be signed in. But once they click the sign in button, they can 'get in'.</p>
<p>Also, note that you imported the <code>useState()</code> hook at the top.</p>
<p>You then created variables that handle signing in, signing out, and setting the <code>set</code> function to <code>true</code> and <code>false</code>, respectively – that is <code>handleSignin</code> and <code>handleSignout</code>.</p>
<p>After that, you created an <code>onClick</code> handler that listens for a click on the button and triggers an action. This action is directed by the Conditional (ternary) Operator.</p>
<p>So how does the ternary operator work? Here's <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator">what the MDN has to say</a>:</p>
<blockquote>
<p>"The <strong>conditional (ternary) operator</strong> is the only JavaScript operator that takes three operands: a condition followed by a question mark (<code>?</code>), then an expression to execute if the condition is <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Truthy">truthy</a> followed by a colon (<code>:</code>), and finally the expression to execute if the condition is <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Falsy">falsy</a>.   </p>
<p>This operator is frequently used as an alternative to an <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else"><code>if...else</code></a> statement."</p>
</blockquote>
<p>This means that if you click the sign in button, you are ushered in and receive the welcome message. Once you click the sign out button, you are prompted to sign in, with the 'please sign in' message.</p>
<h2 id="heading-how-to-use-the-usestate-hook-in-a-react-counter-app">How to Use the <code>useState()</code> Hook in a React Counter App</h2>
<p>This example will help show how you can use <code>useState()</code> to update your state through clicks.</p>
<p>The idea behind this simple counter is that your clicks are counted. So, if you click the button 12 times the counter updates to 12. Note that the button updates on every click/count.</p>
<pre><code class="lang-react">import React from 'react';


const Newcounter = () =&gt; {
    return (
        &lt;div&gt;
            &lt;button type="button"&gt;You will see the count here&lt;/button&gt;
        &lt;/div&gt;
    )
}


export default Newcounter;
</code></pre>
<p>To make the counter functional, you need to use the hook as shown below (and once again, don't forget to import <code>useState()</code> before using it):</p>
<pre><code class="lang-react">const [count, setCount] = useState(0)
</code></pre>
<p>You will then create another variable that increments the counts from 0 to 1, 2, 3....</p>
<pre><code class="lang-react">const incrementCount = () =&gt; { setCount (count + 1) }
</code></pre>
<p>You can now go forth and return the incremented count using the <code>onClick</code> handler as shown below:</p>
<pre><code class="lang-react">import React, { useState } from 'react';


const Newcounter = () =&gt; {
    const [count, setCount] = useState(0)

    const incrementCount = () =&gt; {
        setCount(count + 1)

    }
    return (
        &lt;div&gt;
            &lt;button type="button" onClick={incrementCount}&gt;You clicked  
            {count} times&lt;/button&gt;
        &lt;/div&gt;
    )
}


export default Newcounter;
</code></pre>
<h2 id="heading-how-to-use-the-usestate-hook-in-a-form-in-react">How to Use the <code>useState()</code> Hook in a Form in React</h2>
<p>Forms utilise <code>useState()</code> by allowing the developer to set an empty state that uses the <code>set</code> function to handle what the user type in as their input. </p>
<p>Here, you basically want to to collect the name and email of users through a form and then submit the info.</p>
<p>Below is a simple form to demonstrate how the <code>useState()</code> hook makes this possible.</p>
<p>Here's the form you'll be working with:</p>
<pre><code class="lang-react">import React from 'react'

const Theform
 = () =&gt; {
  return (
    &lt;div&gt;
        &lt;form&gt;
            &lt;input type="text" placeholder="enter your name" required /&gt;
            &lt;input type="email" placeholder="enter your email" required /&gt;
            &lt;button type="submit"&gt;Submit&lt;/button&gt;
        &lt;/form&gt;

    &lt;/div&gt;
  )
}

export default Theform;
</code></pre>
<p>You will need to import the hook to your file. After that, use the <code>useState</code> hook to set the name and email to null as you wait for the user to input their details.</p>
<p>Afterwards, you will create an arrow function with the <code>handleSubmit</code> that executes the <code>preventDefault()</code> method. <code>console.log</code> the name of the user and their email so you can get these details using the <code>onSubmit()</code> event handler.</p>
<p>Once that's done you can then use the <code>set</code> function for both the name and email to target a change in the input and get the value of the input which you initialised as <code>user</code> and <code>email</code> in your <code>useState()</code> hook.</p>
<p>Remember that the <code>useState</code> hook uses that <code>set</code> function for re-rendering. In this, you are re-rendering the new values the user has added in the form. That's why you are setting the value in your input as <code>value={user}</code>.</p>
<pre><code class="lang-react">import React, { useState }from 'react'

const Theform
 = () =&gt; {

  const [user, setUser] = useState('')
  const [email, setEmail] = useState('')

  const handleSubmit = (e) =&gt; {
    e.preventDefault()
    console.log(user, email)

  }
  return (
    &lt;div&gt;
        &lt;form onSubmit={handleSubmit}&gt;
            &lt;input type="text" placeholder="enter your name"  onChange={(e) 
            =&gt; {setUser(e.target.value)}} value ={user} required /&gt;

            &lt;input type="email" placeholder="enter your email" onChange={(e)  
            =&gt; {setEmail(e.target.value)}} value={email} required /&gt;
            &lt;button type="submit"&gt;Submit&lt;/button&gt;

        &lt;/form&gt;

    &lt;/div&gt;
  )
}

export default Theform;
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article you have learned about the <code>useState()</code> hook in React by considering three different examples. Remember, just like all other React Hooks, the useState() hook abides by the general rules of React hooks.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Prevent Infinite Loops When Using useEffect() in ReactJS ]]>
                </title>
                <description>
                    <![CDATA[ By Roy Chng The useEffect hook in React has become a common tool for managing side effects in functional components. But there's a common pitfall when using it: the potential for infinite loops. These can cause performance issues and disrupt the inte... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/prevent-infinite-loops-when-using-useeffect-in-reactjs/</link>
                <guid isPermaLink="false">66d460c7c7632f8bfbf1e491</guid>
                
                    <category>
                        <![CDATA[ Loops ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ react hooks ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 26 Apr 2023 14:07:12 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/preventing-infinite-loops-react.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Roy Chng</p>
<p>The <code>useEffect</code> hook in React has become a common tool for managing side effects in functional components. But there's a common pitfall when using it: the potential for infinite loops. These can cause performance issues and disrupt the intended behavior of components. </p>
<p>In this tutorial, we will explore how to prevent infinite loops when using <code>useEffect</code> in React.</p>
<p>You use the <code>useEffect</code> hook in functional components in React to manage side effects, such as fetching data from an API, updating the DOM, or subscribing to events that are external to React. </p>
<h1 id="heading-situations-that-cause-infinite-loops">Situations that Cause Infinite Loops</h1>
<h2 id="heading-missing-dependencies">Missing Dependencies</h2>
<p>One common mistake that can cause infinite loops is not specifying a dependency array. <code>useEffect</code> checks if the dependencies have changed after every render of the component. </p>
<p>So, when no dependencies are provided, the effect will run after every single render, which can lead to a continuous loop of updates if state is being updated.</p>
<p> For example, consider the following code:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ExampleComponent</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);

    useEffect(<span class="hljs-function">() =&gt;</span> {
        setCount(<span class="hljs-function">(<span class="hljs-params">count</span>) =&gt;</span> count+<span class="hljs-number">1</span>);
    });
}
</code></pre>
<p>In this example, the following occurs:</p>
<ul>
<li>When the component initially renders, the effect will run.</li>
<li>When the effect is run, it updates a count state, resulting in the component being re-rendered.</li>
<li>Since the component is re-rendered, it causes the <code>useEffect</code> to run again.</li>
<li>This causes the <code>count</code> state to update again, and goes on forever.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/useEffect-code-1-6.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Animation showing process of an infinite loop caused by useEffect</em></p>
<p>This happened because there isn't any dependency array specified, indicating that the effect should be run every time after the component re-renders.</p>
<p>To avoid this, add an empty dependency array:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ExampleComponent</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);

    useEffect(<span class="hljs-function">() =&gt;</span> {
        setCount(<span class="hljs-function">(<span class="hljs-params">count</span>) =&gt;</span> count+<span class="hljs-number">1</span>);
    }, []);
}
</code></pre>
<p>This will ensure that the effect is only executed after the initial rendering of the component.</p>
<p>Alternatively, if your effect depends on a certain state, remember to add it as a dependency:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ExampleComponent</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">const</span> [isLoggedIn, setIsLoggedIn] = useState(<span class="hljs-literal">false</span>);

    useEffect(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-comment">// logic</span>
    }), [isLoggedIn];
}
</code></pre>
<p>That way, the effect is only run initially and when the dependency has changed after the component has re-rendered.</p>
<h2 id="heading-using-references-as-dependencies">Using References as Dependencies</h2>
<p>In JavaScript, data types can be categorized as being reference values or primitive values.</p>
<p>Primitive values are basic data types such as Strings, Booleans, Numbers, Null and Undefined.</p>
<p>On the other hand, reference values are more complex data types such as Arrays and Objects.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/primitive-vs-reference-values.png" alt="Image" width="600" height="400" loading="lazy">
<em>Types of primitive and reference values in JavaScript</em></p>
<p>When a reference value is assigned to a variable, the value and location to that value is stored and the variable will only point to that location.</p>
<p>Whereas with a primitive value, the variable is directly assigned to the primitive's value. The value is stored on a stack, a data structure used to store static data.</p>
<p>With reference values such as Functions and Objects, they are stored in a heap, a data structure used for dynamic memory allocation, which is useful when storing complex data types. </p>
<p>The variable is then assigned to the location in the stack, which points to the reference value in the heap.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/stack-vs-heap.png" alt="Image" width="600" height="400" loading="lazy">
<em>A Heap is a data structure used to store reference values</em></p>
<p>This is helps make our applications more efficient. Imagine having to create a duplicate of a complex object every time it is re-assigned to a new variable! Instead, the new variable can just point to the same location in the heap.</p>
<p>As useful as it is, reference values can be problematic when used as a dependency. This is because React will compare the location of the reference value if it is used as a dependency instead of the value's contents.</p>
<p>For example, consider the component:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ExampleComponent</span>(<span class="hljs-params">props</span>)</span>{
    <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">1</span>);
    <span class="hljs-keyword">let</span> data = {
        <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>,
        <span class="hljs-attr">b</span>: <span class="hljs-number">2</span>
    };
    useEffect(<span class="hljs-function">() =&gt;</span> {
        setCount(<span class="hljs-function">(<span class="hljs-params">count</span>) =&gt;</span> count+<span class="hljs-number">1</span>);
        <span class="hljs-comment">//other logic</span>
    }, [data]);
}
</code></pre>
<p>In this case, the following occurs:</p>
<ul>
<li>When the component initially renders, the effect is run</li>
<li>When the effect is run, the state is updated. This causes the component to be re-rendered</li>
<li>When the component is re-rendered, a new <code>data</code> object is created, so its reference location is different from the previous</li>
<li>This causes the effect to run again since the dependency <code>data</code> object has changed</li>
<li>The cycle repeats, causing an infinite loop</li>
</ul>
<p>To prevent this from happening, we can use the <code>useRef</code> hook. It allows us to re-use the same value between re-renders.</p>
<p>This hook allows us to store values that will persist between renders, so the object's reference location will be the same throughout all render cycles. </p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ExampleComponent</span>(<span class="hljs-params">props</span>)</span>{
    <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">1</span>);
    <span class="hljs-keyword">const</span> data = useRef({
        <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>,
        <span class="hljs-attr">b</span>: <span class="hljs-number">2</span>,
    });
    useEffect(<span class="hljs-function">() =&gt;</span> {
        setCount(<span class="hljs-function">(<span class="hljs-params">count</span>) =&gt;</span> count+<span class="hljs-number">1</span>);
        <span class="hljs-comment">// logic</span>
    }, [data.current]);

    <span class="hljs-comment">// rest of component</span>
}
</code></pre>
<p>The <code>useRef</code> hook takes in an initial value and returns a single object with a property called <code>current</code>.</p>
<p>The <code>current</code> property will be the value passed into the <code>useRef</code> hook, and will be the same throughout all renders of the component.</p>
<p>This ensures the effect doesn't run in an infinite loop since the dependency in the <code>useEffect</code> hook will no longer change with each render of the component.</p>
<p>Note that you can also change the value of the <code>data.current</code> property. For example:</p>
<pre><code class="lang-js">data.current = {<span class="hljs-attr">c</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">d</span>: <span class="hljs-number">4</span>}
</code></pre>
<p>By changing the value of <code>data.current</code>, it <strong>will not</strong> trigger the component to re-render and React is <strong>not</strong> aware of this change.</p>
<h2 id="heading-using-functions-as-dependencies">Using Functions as Dependencies</h2>
<p>Another reason that <code>useEffect</code> may be causing an infinite loop is if you use a function as a dependency.</p>
<p>Since a function is a reference value in JavaScript, we encounter the same issue with using objects as dependencies.</p>
<p>For example, if we have a function in our component, the function will be re-created every time the component is re-rendered:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ExampleComponent</span>(<span class="hljs-params">props</span>)</span>{
    <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">1</span>);
    <span class="hljs-keyword">const</span> submitForm = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
        <span class="hljs-comment">// logic</span>
    };
    useEffect(<span class="hljs-function">() =&gt;</span> {
        setCount(<span class="hljs-function">(<span class="hljs-params">count</span>) =&gt;</span> count+<span class="hljs-number">1</span>);
        <span class="hljs-comment">// logic</span>
    }, [submitForm]);

    <span class="hljs-comment">// rest of component</span>
}
</code></pre>
<p>So when the component initially renders:</p>
<ul>
<li>The effect is run initially, causing the <code>count</code> state to update</li>
<li>Since the state has been updated, the component re-renders, causing the <code>submitForm</code> function to be re-created</li>
<li>The effect will run again as the <code>submitForm</code> dependency of the <code>useEffect</code> hook has changed</li>
<li>When the effect runs again, the <code>count</code> state is updated and the loop goes on </li>
</ul>
<p>To avoid the function from being re-created every time the component is re-rendered, we can use the <code>useCallback</code> hook:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ExampleComponent</span>(<span class="hljs-params">props</span>)</span>{
    <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">1</span>);
    <span class="hljs-keyword">const</span> submitForm = useCallback(<span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
        <span class="hljs-comment">// logic</span>
    }, []);
    useEffect(<span class="hljs-function">() =&gt;</span> {
        setCount(<span class="hljs-function">(<span class="hljs-params">count</span>) =&gt;</span> count++);
        <span class="hljs-comment">// logic</span>
    }, [submitForm]);

    <span class="hljs-comment">// rest of component</span>
}
</code></pre>
<p>The <code>useCallback</code> hook also accepts two arguments, the first being the function that needs to be cached and stored without changing between renders, and the second being a dependency array. If the dependencies in the <code>useCallback</code> hook changes, the function is re-created.</p>
<p>So, similar to using <code>useEffect</code>, we can use an empty dependency array to ensure the function isn't being re-created between renders.</p>
<p>This prevents the effect from running in an infinite loop when a function is used as a dependency.</p>
<h2 id="heading-summary">Summary</h2>
<p>The <code>useEffect</code> hook in React is necessary when working with side effects in your React components. But even with experience, common mistakes can lead to infinite loops in your components. Be sure to watch out for missing dependencies, and using references or functions as dependencies when that happens.</p>
<p>We also took a look at how to use the <code>useRef</code> and <code>useCallback</code> hooks to prevent objects from being re-created in between renders.</p>
<p>If you enjoy my writing, consider checking out my <a target="_blank" href="https://www.youtube.com/@turbinethree">YouTube channel</a> for more.</p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ React Hooks Tutorial – How to Use the useReducer Hook ]]>
                </title>
                <description>
                    <![CDATA[ State is an important part of a React application. Most functionalities involve making state updates in your component. But as your application grows, state updates become more and more complex. These complex state updates might get overwhelming when... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/usereducer-hook-react/</link>
                <guid isPermaLink="false">66d851669cec6e68c5591f94</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ react hooks ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kunal Nalawade ]]>
                </dc:creator>
                <pubDate>Mon, 30 Jan 2023 23:15:08 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/photo-1672309046475-4cce2039f342.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>State is an important part of a React application. Most functionalities involve making state <code>updates</code> in your component.</p>
<p>But as your application grows, state updates become more and more complex. These complex state updates might get overwhelming when you revisit your code.</p>
<p>There is a different way of handling state updates, and that's by using reducers. But what are reducers? How do you use them? What does the <code>useReducer</code> hook do? In this post, I'll answer all these questions.</p>
<h2 id="heading-what-is-a-reducer-and-why-do-you-need-it">What Is a Reducer and Why do You Need It?</h2>
<p>Let's take an example of a To-Do app. This app involves adding, deleting, and updating items in the todo list. The update operation itself may involve updating the item or marking it as complete.</p>
<p>When you implement a todo list, you'll have a state variable <code>todoList</code> and make state updates to perform each operation. However, these state updates may appear at different places, sometimes not even inside the component.</p>
<p>To make your code more readable, you can move all your state updates into a single function that can exist outside your component. While performing the required operations, your component just has to call a single method and select the operation it wants to perform.</p>
<p>The function which contains all your state updates is called the <strong>reducer</strong>. This is because you are reducing the state logic into a separate function. The method you call to perform the operations is the <strong>dispatch</strong> method.</p>
<h2 id="heading-how-the-usereducer-hook-works">How the useReducer Hook Works</h2>
<p>You can add a reducer to your component using the <code>useReducer</code> hook. Import the useReducer method from the library like this:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> { useReducer } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
</code></pre>
<p>The <code>useReducer</code> method gives you a state variable and a <code>dispatch</code> method to make state changes. You can define state in the following way:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> [state, dispatch] = useReducer(reducerMethod, initialValue)
</code></pre>
<p>The reducer method contains your state logic. You can choose which state logic to call using the <code>dispatch</code> method. The state can also have some initial value similar to the <code>useState</code> hook.</p>
<h2 id="heading-usereducer-hook-example">useReducer Hook Example</h2>
<p>Let's take a simple example where we have a list of users. We can add a new user, delete an existing user, and update user details. Normally, we would create a state variable <code>user</code> and perform state updates at different places.</p>
<p>Let's try doing the same using reducers:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> [users, dispatch] = useReducer(reducerMethod, userData);
</code></pre>
<p>Use the following initial data:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> userData = [
    {
        <span class="hljs-attr">id</span>:<span class="hljs-number">1</span>,
        <span class="hljs-attr">name</span>: <span class="hljs-string">'kunal'</span>,
        <span class="hljs-attr">age</span>: <span class="hljs-number">22</span>,
        <span class="hljs-attr">admin</span>: <span class="hljs-literal">true</span>
    },
    {
        <span class="hljs-attr">id</span>:<span class="hljs-number">2</span>,
        <span class="hljs-attr">name</span>: <span class="hljs-string">'rounak'</span>,
        <span class="hljs-attr">age</span>: <span class="hljs-number">23</span>,
        <span class="hljs-attr">admin</span>: <span class="hljs-literal">false</span>
    },
    {
        <span class="hljs-attr">id</span>:<span class="hljs-number">3</span>,
        <span class="hljs-attr">name</span>: <span class="hljs-string">'utkarsh'</span>,
        <span class="hljs-attr">age</span>: <span class="hljs-number">22</span>,
        <span class="hljs-attr">admin</span>: <span class="hljs-literal">false</span>
    },   
]
</code></pre>
<h3 id="heading-how-to-define-the-reducer-method">How to Define the Reducer Method</h3>
<p>The reducer method contains our state updates. The method takes two arguments, the current state value and an action object. The action object contains the type of the action and additional data needed to perform the update.</p>
<p>We'll perform three types of updates – for user added, updated, and deleted. We'll use switch-case to select the type of operation to be performed.</p>
<pre><code class="lang-python">const reducerMethod = (users, action) =&gt; {
    switch(action.type) {
        // State updates here
    }
}
</code></pre>
<p>The <code>type</code> field contains the name of the operation to be performed. This is a string and you can set any value you want. Just make sure it's relevant to the action being performed for better readability. Let's perform the add operation first:</p>
<pre><code class="lang-python">case <span class="hljs-string">'addUser'</span>: {
    <span class="hljs-keyword">return</span> [
        ...users,
        action.newUser
    ]
}
</code></pre>
<p>The logic for updating state is similar to <code>setState</code>. Here, you return a new state value rather than making changes to the state variable directly.</p>
<p>Let's perform the update operation now. While performing the update operation, the dispatch method passes an <code>updatedUser</code> object to update an existing user. This additional data is passed through the <code>action</code> object.</p>
<pre><code class="lang-python">case <span class="hljs-string">'updateUser'</span>: {
    <span class="hljs-keyword">return</span> users.map(user =&gt; {
        <span class="hljs-keyword">if</span>(user.id == action.updatedUser.id)
            <span class="hljs-keyword">return</span> action.updatedUser
        <span class="hljs-keyword">return</span> user;
    })
}
</code></pre>
<p>Now, for the delete operation, the <code>dispatch</code> method passes only the <code>id</code> of the object so that the state array can filter it out.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">case</span> <span class="hljs-string">'deleteUser'</span>: {
    <span class="hljs-keyword">return</span> users.filter(<span class="hljs-function"><span class="hljs-params">user</span> =&gt;</span> user.id !== action.id)
}
</code></pre>
<p>Let's also have a default case if an action other than the above three is specified.</p>
<pre><code class="lang-python">default: {
    // Handle error here
}
</code></pre>
<p>Now, let's create the components that would actually use this reducer.</p>
<p>Display the list of users in the <code>UserDetails</code> component with the following props:</p>
<pre><code class="lang-javascript">&lt;UsersList users={users}
           handleUpdateUser={handleUpdateUser}
           handleDeleteUser={handleDeleteUser}
 /&gt;
</code></pre>
<p>Also, create a form to add new users in the <code>AddUserForm</code> component.</p>
<pre><code class="lang-javascript">&lt;AddUserForm handleAddUser={handleAddUser} /&gt;
</code></pre>
<p>I have not mentioned the actual implementations of the components here, as the focus is only on the state update part.</p>
<p>We'll make the state updates inside the handler methods by calling the <code>dispatch</code> method and passing the type of the state update with some data. For the add operation, pass the new user to be added.</p>
<pre><code class="lang-python">const handleAddUser = (user) =&gt; {
    dispatch({
        type: <span class="hljs-string">'addUser'</span>,
        newUser: user
    })
}
</code></pre>
<p>Similarly, you can implement <code>handleUpdateUser</code> and <code>handleDeleteUser</code>.</p>
<pre><code class="lang-python">const handleUpdateUser = (updatedUser) =&gt; {
    dispatch({
        type: <span class="hljs-string">'updateUser'</span>,
        updatedUser: updatedUser
    })
}

const handleDeleteUser = (userId) =&gt; {
    dispatch({
        type: <span class="hljs-string">'deleteUser'</span>,
        id: userId
    })
}
</code></pre>
<p>The <code>newUser</code>, <code>updatedUser</code> and <code>userId</code> are parameters passed from the <code>AddUserForm</code> and <code>UsersList</code> components. They contain the required data to make the state updates.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>For any feature you create, state updates form a crucial part of the implementation in React. As the complexity of the application increases, so does the number of state updates.</p>
<p>In this post, I explained what a reducer is and why we need it. With the help of an example, I showed you how convenient it is to have all the state updates in one place in a separate function. This makes the code more readable and accessible.</p>
<p>I hope this tutorial helped eliminate any confusion regarding the <code>useReducer</code> hook. I have tried to explain it in very simple terms.</p>
<p>If you are unable to understand the content or find the explanation unsatisfactory, let me know. New ideas are always appreciated! Feel free to connect with me on Twitter. Till then, goodbye!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use React Hooks – Full Tutorial for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ Hi everyone! Hooks are one of the main features of modern React code and one of the first concepts you should get comfortable with when learning about this library. In this article I'm going to explain some of the most useful hooks React provides us ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/full-guide-to-react-hooks/</link>
                <guid isPermaLink="false">66d45efc36c45a88f96b7cdb</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ react hooks ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ German Cocca ]]>
                </dc:creator>
                <pubDate>Tue, 17 Jan 2023 01:04:42 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/steve-johnson-6sB8gMRlEAU-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi everyone! Hooks are one of the main features of modern React code and one of the first concepts you should get comfortable with when learning about this library.</p>
<p>In this article I'm going to explain some of the most useful hooks React provides us with, how they work, and examples of situations in which we can use them.</p>
<p>Hope you enjoy the reading. Let's go!</p>
<h1 id="heading-table-of-contents">Table of Contents</h1>
<ul>
<li><p><a class="post-section-overview" href="#heading-a-bit-of-history-about-react-and-what-hooks-are-for">A bit of history about React and what hooks are for</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-frequently-used-react-hooks">Frequently used React hooks</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-usestate-hook">UseState hook</a></p>
</li>
<li><p><a class="post-section-overview" href="#useEffect-hook">UseEffect hook</a></p>
</li>
<li><p><a class="post-section-overview" href="#useContext-hook">UseContext hook</a></p>
</li>
<li><p><a class="post-section-overview" href="#useRef-hook">UseRef hook</a></p>
</li>
<li><p><a class="post-section-overview" href="#useReducer-hook">UseReducer hook</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-some-less-common-but-still-useful-hooks">Some less common but still useful hooks</a></p>
<ul>
<li><p><a class="post-section-overview" href="#useCallback-hook">UseCallback hook</a></p>
</li>
<li><p><a class="post-section-overview" href="#useMemo-hook">UseMemo hook</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-custom-react-hooks">Custom React hooks</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-round-up">Round up</a></p>
</li>
</ul>
<h1 id="heading-a-bit-of-history-about-react-and-what-hooks-are-for">A bit of history about React and what hooks are for</h1>
<p>As you may know, React is a open-source library used to build user interfaces in a simpler and more efficient way than tools that came before (vanilla JS and jQuery mainly). It was developed by Meta (aka Facebook) and released to the public in 2013.</p>
<p>Hooks were a feature introduced years later in 2016 (in React's 16.8 version). Just to have an idea of what hooks are for and why are they improvement over what was done before, let's view an example of "pre-hooks" code against some modern React "post-hooks" code.</p>
<p>In old React code, we used class components. These had a <code>render</code> method which contained the JSX responsible for rendering the UI.</p>
<p>And if we wanted this component to store a state, we had to declare it within a constructor method and change it by calling <code>this.setState</code>. Beneath is a short example for you to have an idea:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// javascript</span>
<span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Counter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
    <span class="hljs-keyword">constructor</span>(props) {
      <span class="hljs-built_in">super</span>(props)
      <span class="hljs-built_in">this</span>.state = { <span class="hljs-attr">count</span>: <span class="hljs-number">0</span> }
    }

    handleIncrement = <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">count</span>: prevState.count - <span class="hljs-number">1</span> };
      })
    }

    handleDecrement = <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">count</span>: prevState.count + <span class="hljs-number">1</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">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{this.handleIncrement}</span>&gt;</span>Increment<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{this.handleDecrement}</span>&gt;</span>Decrement<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>

          <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>{this.state.count}<span class="hljs-tag">&lt;/<span class="hljs-name">h2</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> Counter
</code></pre>
<p>It's important to mention that function components (what we use nowadays) were available in "pre-hooks" React too. But we could only use them for stateless components – meaning components that didn't store state and weren't responsible of any complex logic apart from just rendering UI.</p>
<p>With the incorporation of hooks, we can now use function components (and their more straight-forward and less verbose composition) together with all the more complex functionalities class components offered us.</p>
<p>In short, hooks are things we use to implement logic and functionalities in our components.</p>
<p>Here's another example were we transform what we had in our class component into a functional one:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// javascript</span>
<span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>

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

    <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>)

    <span class="hljs-keyword">const</span> handleIncrement = <span class="hljs-function">() =&gt;</span> setCount(count+<span class="hljs-number">1</span>)
    <span class="hljs-keyword">const</span> handleDecrement = <span class="hljs-function">() =&gt;</span> setCount(count<span class="hljs-number">-1</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">"App"</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> handleIncrement()}&gt;Increment<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> handleDecrement()}&gt;Decrement<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>{count}<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>                    
    )
}
</code></pre>
<h1 id="heading-frequently-used-react-hooks">Frequently Used React Hooks</h1>
<p>Now you have an idea of what hooks are for and why are they better than what was before. So let's take a look at the most used ones, on what occasions are they useful, and how to implement them.</p>
<h2 id="heading-usestate-hook">UseState hook</h2>
<p>In modern React, we build our applications with <strong>functional components</strong>. Components are themselves JavaScript functions, independent and <strong>reusable</strong> bits of code.</p>
<p>The purpose of building the application with components is to have a modular architecture, with a clear separation of concerns. This makes code easier to understand, easier to maintain, and easier to reuse when possible.</p>
<p>The <strong>state is an object that holds information</strong> about a certain component. Plain JavaScript functions don't have the ability to store information. The code within them executes and "disappears" once the execution is finished.</p>
<p>But thanks to state, React functional components can store information even after execution. When we need a component to store or "remember" something, or to act in a different way depending on the environment, state is what we need to make it work this way.</p>
<p>It's important to mention that not all components in a React app must have state. There are stateless components as well which just render its content without the need to store any information, and that's just fine.</p>
<p>Another important thing to mention is that state change is one of the two things that make a React component re-render (the other is a change in props). In this way, the state stores information about the component and also controls its behavior.</p>
<p>In order to implement state in our components, React provides us with a hook called <strong>useState</strong>. Let's see how it works with the following example.</p>
<pre><code class="lang-js"><span class="hljs-comment">// javascript</span>
<span class="hljs-comment">// App.js</span>
<span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{

  <span class="hljs-keyword">const</span> [count, setCount] = useState(<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">"App"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Count is: {count}<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 class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setCount(count+1)}&gt;Add 1<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setCount(count-1)}&gt;Decrease 1<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setCount(count+10)}&gt;Add 10<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setCount(count-10)}&gt;Decrease 10<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setCount(0)}&gt;Reset count<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>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<ul>
<li><p>First we import the hook from React: <code>import { useState } from 'react'</code></p>
</li>
<li><p>Then we initialize the state: <code>const [count, setCount] = useState(0)</code></p>
</li>
</ul>
<p>Here we provide a variable name for the state (<code>count</code>) and a function name we'll use every time we need to update that state (<code>setCount</code>). Then we set the initial value of the state (<code>0</code>), which will be the value loaded by default every time the app starts.</p>
<ul>
<li>Lastly, as mentioned above, every time we want to update the state, we have to use the function we declared: <code>setCount</code>. To use it, we just need to call it passing it the new state we want as a parameter. That is, if we want to add 1 to the previous estate, we call <code>setCount(count+1)</code>.</li>
</ul>
<p>As mentioned as well, this will cause an update of the state and the re-render of the component. Which in our app means we'll see on the screen that the counter is going up.</p>
<p>It's important to mention that the setState function is <strong>asynchronous</strong>. So if we try to read the state immediately after updating it, like this:</p>
<pre><code class="lang-js">&lt;button onClick={<span class="hljs-function">() =&gt;</span> {
          setCount(count+<span class="hljs-number">1</span>)
          <span class="hljs-built_in">console</span>.log(count)
}}&gt;Add <span class="hljs-number">1</span>&lt;/button&gt;
</code></pre>
<p>we would get the previous value of the state, without the update.</p>
<p>The correct way of reading state after the update would be using the <strong>useEffect</strong> hook. It lets us execute a function after every component re-render (by default) or after any particular variable where we declare changes.</p>
<p>Something like this:</p>
<pre><code class="lang-js">useEffect(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(value), [value])
</code></pre>
<p>Also, the fact that useState is asynchronous has implications when considering very frequent and quick state changes.</p>
<p>Take, for example, the case of a user that presses the ADD button many times in a row, or a loop that emits a click event a certain number of times.</p>
<p>By updating state like <code>setCount(count+1)</code> we take the risk that <code>count</code> won't yet be updated when the next event is fired.</p>
<p>For example, let's say at the start <code>count = 0</code>. Then <code>setCount(count+1)</code> is called and the state is asynchronously updated.</p>
<p>But then again <code>setCount(count+1)</code> is called, before the state update was completed. This means that still <code>count = 0</code>, which means that the second <code>setCount</code> won't update the state correctly.</p>
<p>A more defensive approach would be to pass <code>setCount</code> a callback, like so: <code>setCount(prevCount =&gt; prevCount+1)</code>.</p>
<p>This makes sure that the value to update is the most recent one and keeps us away from the problem mentioned above. Every time we perform updates on a previous state we should use this approach.</p>
<p>If you'd like to take a more in-depth look at ways to manage state in React, you can take a look at <a target="_blank" href="https://www.freecodecamp.org/news/how-to-manage-state-in-a-react-app/">this article</a> I wrote a while ago.</p>
<h2 id="heading-useeffect-hook">UseEffect hook</h2>
<p>Together with useState, useEffect will probably be the hook you use the most when developing a React app. It's like the bread and butter for the React dev.</p>
<p>UseEffect allows you to run a side effect on your component. Side effect basically means something that happens after some other specific thing happens.</p>
<p>A typical use case is to fetch data once the component has been mounted. Let's say we have a function called <code>fetchData</code> which is responsible for that – our useEffect hook might look like this:</p>
<pre><code class="lang-plaintext">  useEffect(() =&gt; { fetchData() }, [])
</code></pre>
<p>The structure of this hook is quite simple. It accepts two arguments. First we have a callback which executes our function and then we have an array called "array of dependencies". If we leave it empty like it is in the example, the callback will execute after the component renders.</p>
<p>Now let's say we want our side effect to run after a variable changes. Following the previous example we used for the useState hook, for our side effect after the <code>count</code> variable changes, we could set useEffect like this:</p>
<pre><code class="lang-plaintext">// javascript
// App.js
import { useState } from 'react'

function App() {

  const [count, setCount] = useState(0)

  useEffect(() =&gt; { console.log('Count has changed!') }, [count])

  return (
    &lt;div className="App"&gt;
      &lt;p&gt;Count is: {count}&lt;/p&gt;

      &lt;div&gt;
        &lt;button onClick={() =&gt; setCount(count+1)}&gt;Add 1&lt;/button&gt;
        &lt;button onClick={() =&gt; setCount(count-1)}&gt;Decrease 1&lt;/button&gt;

        &lt;button onClick={() =&gt; setCount(count+10)}&gt;Add 10&lt;/button&gt;
        &lt;button onClick={() =&gt; setCount(count-10)}&gt;Decrease 10&lt;/button&gt;

        &lt;button onClick={() =&gt; setCount(0)}&gt;Reset count&lt;/button&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  )
}

export default App
</code></pre>
<p>A third and last thing to mention about useEffect is the possibility to return a "cleanup" function. This "cleanup" function will execute when the component unmounts. Following our previous example, adding a cleanup function might look like this:</p>
<pre><code class="lang-javascript">  useEffect(<span class="hljs-function">() =&gt;</span> {
    fetchData()
    <span class="hljs-keyword">return</span> cleanUp()
  }, [])
</code></pre>
<p>Cleanup functions in useEffect are normally used to cancel subscriptions to avoid React trying to update the state of a component that has already been unmounted.</p>
<p>For more info about useEffect's cleanup function, you can refer to <a target="_blank" href="https://blog.logrocket.com/understanding-react-useeffect-cleanup-function/">this</a> article.</p>
<h2 id="heading-usecontext-hook">UseContext hook</h2>
<p>React context API was released in 2016 with React's 16.3 version. What context does in React is to provide a solution for <a target="_blank" href="https://www.freecodecamp.org/news/avoid-prop-drilling-with-react-context-api/">prop drilling</a>.</p>
<p>Prop drilling refers to the situation in which we have a parent component that stores a state. And beneath that parent, we have many levels of children components.</p>
<p>If we need to render that state in a child component that is deeply nested in that structure, the solution would be to pass the state as props all along the component chain.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/propDrilling.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>A graphic of prop drilling</em></p>
<p>This option works just fine. The problem is we would need to repeat the same code in many different places, which if we ever need to change our code later on (you'll always have to do this sooner or later) is something very tedious to work with and prone to errors and bugs.</p>
<p>The context API solves this situation by providing "a place" to store state that needs to be consumed from many different parts of our application, and along different levels of the component tree.</p>
<p>The way this works is that the context component will store the given state, and from any given component we can read and update that state, no matter where that component is located. We forget all about props. Instead, we can just work directly with the context and all the components that read that context state will re-render when the state is updated.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/context.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>A graphic of the same situation but using context</em></p>
<p>Now that we have the theoretical foundation, let's see how the useContext hook allows us to use this API. The typical implementation would look something like this. Within a "context" folder we'll have two files. <code>Context.js</code> and <code>ContextProvider.js</code>.</p>
<p>Within <code>Context.js</code> we'll just initialize the context API by using the <code>createContext</code> function, which takes as an argument the initial state we want to provide (we don't want anything in this case so we can just pass null).</p>
<pre><code class="lang-plaintext">/// Context.js 
import { createContext } from 'react'

const Context = createContext(null)

export default Context

On `ContextProvider.js` we'll import the context we initialized in the previous file. We'll also initialize the states we want to consume later on and update from our app's components. Finally, we return the context provider and with the `value` object we pass all the states and setState functions we want to consume later on.

The contextProvider is a HOC. A **higher order component or HOC** is similar to a higher order function in JavaScript (I have an article about that [here](https://gercocca.hashnode.dev/higher-order-functions-and-callbacks)). 

Higher order functions are functions that take other functions as arguments OR return other functions. React HOCs take a component as a prop, and manipulate it to some end without actually changing the component itself. You can think of this like wrapper components.
</code></pre>
<p>/// ContextProvider.js import { useState } from 'react' import Context from './Context'</p>
<p>const ContextProvider = ({children}) =&gt; {</p>
<p>const [darkModeOn, setDarkModeOn] = useState(true) const [englishLanguage, setEnglishLanguage] = useState(true)</p>
<p>return ( &lt;Context.Provider value={{ darkModeOn, setDarkModeOn, englishLanguage, setEnglishLanguage }} &gt; {children} &lt;/Context.Provider&gt; ) }</p>
<p>export default ContextProvider</p>
<pre><code class="lang-plaintext">
In our `App.js` file, we'll wrap all the components that we want to be able to interact with the state with our contextProvider. In this case we want the whole application to be able to consume and update the context, so we wrap it all.
</code></pre>
<p>/// App.js</p>
<p>import './App.scss' import { Suspense, lazy } from 'react' import { BrowserRouter as Router, Routes, Route } from 'react-router-dom' import ContextProvider from './context/ContextProvider' import ErrorBoundary from './ErrorBoundary'</p>
<p>const Header = lazy(() =&gt; import ('./components/header/Header')) const AboutPage = lazy(() =&gt; import ('./components/aboutPage/AboutPage')) const ProjectsPage = lazy(() =&gt; import('./components/projectsPage/ProjectsPage')) const ShortrProject = lazy(() =&gt; import('./components/projectsPage/shortrProject/ShortrProject')) const MixrProject = lazy(() =&gt; import('./components/projectsPage/mixrProject/MixrProject')) const HelprProject = lazy(() =&gt; import('./components/projectsPage/helprProject/HelprProject')) const MyWebsiteProject = lazy(() =&gt; import('./components/projectsPage/myWebsiteProject/MyWebsiteProject')) const CurriculumPage = lazy(() =&gt; import('./components/curriculumPage/CurriculumPage')) const BlogPage = lazy(() =&gt; import('./components/blogPage/BlogPage')) const ContactPage = lazy(() =&gt; import('./components/contactPage/ContactPage'))</p>
<p>export default function App() { return (</p>
<p>&lt;Suspense fallback={&lt;&gt;&lt;/&gt;}&gt;</p>
<p>&lt;Route path='/' element={&lt;Suspense fallback={&lt;&gt;&lt;/&gt;}&gt;}/&gt;</p>
<p>&lt;Route path='/projects' element={&lt;Suspense fallback={&lt;&gt;&lt;/&gt;}&gt;}/&gt;</p>
<p>&lt;Route path='/projects/helpr' element={&lt;Suspense fallback={&lt;&gt;&lt;/&gt;}&gt;}/&gt;</p>
<p>&lt;Route path='/projects/myWebsite' element={&lt;Suspense fallback={&lt;&gt;&lt;/&gt;}&gt;}/&gt;</p>
<p>&lt;Route path='/projects/mixr' element={&lt;Suspense fallback={&lt;&gt;&lt;/&gt;}&gt;}/&gt;</p>
<p>&lt;Route path='/projects/shortr' element={&lt;Suspense fallback={&lt;&gt;&lt;/&gt;}&gt;}/&gt;</p>
<p>&lt;Route path='/curriculum' element={&lt;Suspense fallback={&lt;&gt;&lt;/&gt;}&gt;}/&gt;</p>
<p>&lt;Route path='/blog' element={&lt;Suspense fallback={&lt;&gt;&lt;/&gt;}&gt;}/&gt;</p>
<p>&lt;Route path='/contact' element={&lt;Suspense fallback={&lt;&gt;&lt;/&gt;}&gt;}/&gt;</p>
<p>) }</p>
<pre><code class="lang-plaintext">
Finally, from the component we want to read/update context state, we import the context and the useContext hook and destructure the states and functions in the following way (and just use the regular state and setState functions).
</code></pre>
<p>import { useContext, useState } from 'react' import Context from '../../context/Context'</p>
<p>import { Link, NavLink } from 'react-router-dom'</p>
<p>const Header = () =&gt; {</p>
<p>const { darkModeOn, setDarkModeOn, englishLanguage, setEnglishLanguage } = useContext(Context)</p>
<p>const [showMobileMenu, setShowMobileMenu] = useState(false)</p>
<p>const openMobileMenu = () =&gt; { document.body.classList.add('mobileMenu-open') setShowMobileMenu(true) }</p>
<p>const hideMobileMenu = () =&gt; { document.body.classList.remove('mobileMenu-open') setShowMobileMenu(false) }</p>
<p>return ( &lt;header className={darkModeOn ? 'header header-dark' : 'header header-light'}&gt;</p>
<h1 id="heading-german-cocca">Germán Cocca</h1>
<h1 id="heading-g">G</h1>
<ul>
<li><p>{englishLanguage ? 'About' : 'Sobre mi'}</p>
</li>
<li><p>{englishLanguage ? 'Projects' : 'Proyectos'}</p>
</li>
<li><p>Blog</p>
</li>
<li><p>Curriculum</p>
</li>
<li><p>{englishLanguage ? 'Contact' : 'Contacto'}</p>
</li>
</ul>
<p>&lt;button data-testid='es-language-btn' className={englishLanguage ? '' : 'selected'} onClick={() =&gt; setEnglishLanguage(false)}&gt;ES &lt;button data-testid='en-language-btn' className={englishLanguage ? 'selected' : ''} onClick={() =&gt; setEnglishLanguage(true)}&gt;EN</p>
<p>&lt;input type='checkbox' data-testid='dark-mode-toggle' id='dark-mode-toggle' aria-checked='true' className='toggle-checkbox' checked={darkModeOn} onClick={() =&gt; setDarkModeOn(!darkModeOn)} /&gt;</p>
<p><a class="post-section-overview" href="#menu">&lt;div className="hamburguer-icon" onClick={() =&gt; showMobileMenu ? hideMobileMenu() : openMobileMenu()}&gt; &lt;div className={!showMobileMenu ? 'line' : 'line top'}&gt; &lt;div className={!showMobileMenu ? 'line' : 'line center'}&gt; &lt;div className={!showMobileMenu ? 'line' : 'line bottom'}&gt;</a></p>
<p>&lt;nav id='mobile-menu' className={showMobileMenu ? 'mobile-menu-active' : 'mobile-menu'}&gt;</p>
<ul>
<li><p>&lt;NavLink to='/' onClick={() =&gt; hideMobileMenu()}&gt;{englishLanguage ? 'About' : 'Sobre mi'}</p>
</li>
<li><p>&lt;NavLink to='/projects' onClick={() =&gt; hideMobileMenu()}&gt;{englishLanguage ? 'Projects' : 'Proyectos'}</p>
</li>
<li><p>&lt;NavLink to='/blog' onClick={() =&gt; hideMobileMenu()}&gt;Blog</p>
</li>
<li><p>&lt;NavLink to='/curriculum' onClick={() =&gt; hideMobileMenu()}&gt;Curriculum</p>
</li>
<li><p>&lt;NavLink to='/contact' onClick={() =&gt; hideMobileMenu()}&gt;{englishLanguage ? 'Contact' : 'Contacto'}</p>
</li>
<li><p>&lt;button className={englishLanguage ? '' : 'selected'} onClick={() =&gt; { setEnglishLanguage(false) hideMobileMenu() }}&gt;ES &lt;button className={englishLanguage ? 'selected' : ''} onClick={() =&gt; { setEnglishLanguage(true) hideMobileMenu() }}&gt;EN</p>
</li>
</ul>
<p>) }</p>
<p>export default Header</p>
<pre><code class="lang-plaintext">
This is a tiny bit more boilerplate than just passing everything through props, but it's a lot more maintainable, simple, and easy to understand once it's set up.

Another interesting thing to mention is that we can have many different contexts in our application. We can separate them into concerns. For example, say we have one for authentication states, another regarding user preferences and configuration, another for payments or whatever... And then we can wrap those contexts only around the specific components that need to use them. 

So if we have a lot of information that needs to be shared around our app, having many different contexts would be a more modular and tidy way to approach this.

## UseReducer hook

UseReducer is a hook that allows us to natively implement reducers in our app to manage complex states. If you're familiar with [Redux](https://redux.js.org/) or similar state management libraries, the word "reducer" probably rings a bell.

Basically, reducers are a kind of function that take in two or more arguments, perform some kind of action with them, and return a single result that follows from the two arguments. 

A **reducer** is a pure function that takes the previous state and an action as an argument, and returns the next state. It's called a reducer because it's the same function type you could pass to an array: `Array.prototype.reduce(reducer, initialValue)`.

But before we dive in to reducers, why do we need this if we already have the useState hook to manage our state? 

Well, a problem that may come up when you're using useState is the case where new state to be set depends on the previous state or when state changes occur very frequently in our application. 

In these occasions, useState may provoke some unexpected and unpredictable behavior. So this is where **reducers** come in to solve this problem.

**useReducer** is the hook Reacts provides that lets us implement reducers to manage our state. Here's an implementation example:

```js
// App.js
import { useReducer } from 'react'
import './App.scss'

function App() {

  function reducer(state, action) {
    switch (action.type) {
      case 'ADD': return { count: state.count + 1 }
      case 'SUB': return { count: state.count - 1 }
      case 'ADD10': return { count: state.count + 10 }
      case 'SUB10': return { count: state.count - 10 }
      case 'RESET': return { count: 0 }
      default: return state
    }
  }

  const [state, dispatch] = useReducer(reducer, { count: 0 })  

  return (
    &lt;div className="App"&gt;
      &lt;p&gt;Count is: {state.count}&lt;/p&gt;

      &lt;div&gt;
        &lt;button onClick={() =&gt; dispatch({type: 'ADD'})}&gt;Add 1&lt;/button&gt;

        &lt;button onClick={() =&gt; dispatch({type: 'SUB'})}&gt;Decrease 1&lt;/button&gt;

        &lt;button onClick={() =&gt; dispatch({type: 'ADD10'})}&gt;Add 10&lt;/button&gt;
        &lt;button onClick={() =&gt; dispatch({type: 'SUB10'})}&gt;Decrease 10&lt;/button&gt;

        &lt;button onClick={() =&gt; dispatch({type: 'RESET'})}&gt;Reset count&lt;/button&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  )
}

export default App
</code></pre>
<ul>
<li><p>We start by importing the hook from React: <code>import { useReducer } from 'react'</code></p>
</li>
<li><p>Then we'll declare a reducer function, which as parameters will take the current state and an action to perform on it. Within it, it will have a switch statement that will read the action type, execute the corresponding action on the state, and return the updated state.</p>
</li>
</ul>
<p>It's common practice to use switch statements on reducers and capital letters to declare the actions.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">reducer</span>(<span class="hljs-params">state, action</span>) </span>{
    <span class="hljs-keyword">switch</span> (action.type) {
      <span class="hljs-keyword">case</span> <span class="hljs-string">'ADD'</span>: <span class="hljs-keyword">return</span> { <span class="hljs-attr">count</span>: state.count + <span class="hljs-number">1</span> }
      <span class="hljs-keyword">case</span> <span class="hljs-string">'SUB'</span>: <span class="hljs-keyword">return</span> { <span class="hljs-attr">count</span>: state.count - <span class="hljs-number">1</span> }
      <span class="hljs-keyword">case</span> <span class="hljs-string">'ADD10'</span>: <span class="hljs-keyword">return</span> { <span class="hljs-attr">count</span>: state.count + <span class="hljs-number">10</span> }
      <span class="hljs-keyword">case</span> <span class="hljs-string">'SUB10'</span>: <span class="hljs-keyword">return</span> { <span class="hljs-attr">count</span>: state.count - <span class="hljs-number">10</span> }
      <span class="hljs-keyword">case</span> <span class="hljs-string">'RESET'</span>: <span class="hljs-keyword">return</span> { <span class="hljs-attr">count</span>: <span class="hljs-number">0</span> }
      <span class="hljs-attr">default</span>: <span class="hljs-keyword">return</span> state
    }
  }
</code></pre>
<ul>
<li>Afterwards, it's time to declare our <strong>useReducer</strong> hook, which looks fairly similar to the useState hook. We declare a <strong>value for our state</strong> ('state' in our case), a <strong>function we'll use to modify it</strong> ('dispatch'), and then useReducer will take the <strong>reducer function</strong> as first parameter and the <strong>default state</strong> as second parameter.</li>
</ul>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> [state, dispatch] = useReducer(reducer, { <span class="hljs-attr">count</span>: <span class="hljs-number">0</span> })
</code></pre>
<ul>
<li>Lastly, to update our state we won't call the reducer directly, but instead we'll call the function we just created ('dispatch'), passing it the corresponding action type we want to execute. Behind the scenes, the dispatch function will connect with the reducer and actually modify the state.</li>
</ul>
<pre><code class="lang-js">&lt;button onClick={<span class="hljs-function">() =&gt;</span> dispatch({<span class="hljs-attr">type</span>: <span class="hljs-string">'ADD'</span>})}&gt;Add <span class="hljs-number">1</span>&lt;/button&gt;
</code></pre>
<p>It's quite a bit more boilerplate than using useState, but useReducer isn't that complex after all.</p>
<p>To sum it up, we just need:</p>
<ul>
<li><p>A reducer, that is the function that will consolidate all possible state changes</p>
</li>
<li><p>A dispatch function, that will send the modifying actions to the reducer.</p>
</li>
</ul>
<p>The thing here is that the UI elements won't be able to update the state directly like they did before when calling setState with a value. Now they will have to call an action type and go through the reducer, which makes state management more modular and predictable.</p>
<p>Also, again if you're familiar with Redux and other state management libraries, you probably noticed that with the Context API and the useReducer hook we can easily implement the same features Redux provides, but natively in React now. So personally, I think for most use cases you don't need a state management library in modern React code.</p>
<p>The story was different before, though, and that's probably why so many state management libraries got popular and many devs are still into them nowadays.</p>
<h2 id="heading-useref-hook">UseRef hook</h2>
<p>The useRef hook is a function that returns a mutable ref object whose <code>.current</code> property is initialized with the passed argument (<code>initialValue</code>). The returned object will persist for the full lifetime of the component.</p>
<p>There are two main uses of useRef: Keeping track of a mutable variable through re-renders, and accessing the DOM nodes or React elements.</p>
<p>We can declare a ref using the useRef hook the following way: <code>const ref = useRef(initialValue)</code>. Then <code>reference.current</code> accesses the reference value, and <code>reference.current = newValue</code> updates the reference value. Pretty simple.</p>
<p>There are 2 things to remember about refs:</p>
<ol>
<li><p>The value of the reference is persisted between component re-renderings.</p>
</li>
<li><p>Updating a reference doesn’t trigger a component re-rendering.</p>
</li>
</ol>
<p>To see an example of this, let's imagine a case where we need to count the number of clicks on a button without re-rendering a component. We could do that like this:</p>
<pre><code class="lang-plaintext">import { useRef } from 'react';

function LogButtonClicks() {
    const countRef = useRef(0);

    const handle = () =&gt; {
        countRef.current++;
        console.log(`Clicked ${countRef.current} times`);
    };

    console.log('I rendered!');

    return &lt;button onClick={handle}&gt;Click me&lt;/button&gt;;
}
</code></pre>
<p>By updating and logging the ref, we avoid the component re-render and achieve our goal. So, the 2 main differences between references and state are:</p>
<ol>
<li><p>Updating a reference doesn’t trigger re-rendering, while updating the state makes the component re-render.</p>
</li>
<li><p>And also... The reference update is synchronous (the updated reference value is available right away), while the state update is asynchronous (the state variable is updated after re-rendering).</p>
</li>
</ol>
<h1 id="heading-some-less-common-but-still-useful-hooks">Some Less Common but Still Useful Hooks</h1>
<p>Here I'll present two hooks that are used for memoization in React. If you're not familiar with memoization, you can refer to <a target="_blank" href="https://www.freecodecamp.org/news/memoization-in-javascript-and-react/">this article</a> I wrote a while ago about it.</p>
<p>Basically memoization means making components "remember" props and state, so they re-render only if props/state have changed and avoided unnecessary re-renders. This improves the app's performance.</p>
<h2 id="heading-usecallback-hook">UseCallback hook</h2>
<p>useCallback memoizes callback functions received as props, so they're not recreated on every re-render. Using useCallback correctly can improve the performance of our app.</p>
<p>The way we can implement it is by wrapping the function we're passing as props to a childr component within the useCallback hook, like this:</p>
<pre><code class="lang-plaintext">import { useCallback } from 'react'
import Child from "./child"

export default function Counter() {

    return (
        &lt;div className="App"&gt;
             &lt;Child name={ useCallback(() =&gt; {console.log('Really Skinny Jack')}, [])  } /&gt;
        &lt;/div&gt;                    
    )
}
</code></pre>
<p>What useCallback does is to hold on to the value of the function despite the parent component re-rendering. This means that the child prop will remain the same as long as the function value remains the same as well. And that solves the problem of unnecessary child re-rendering.</p>
<p>To use it, we just need to wrap the useCallback hook around the function we're declaring. useCallback also has a dependency array, like useEffect. In the array present in the hook, we can declare variables that would trigger the change of the function value when the variable changes too (exactly the same way useEffect works).</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> testingTheTest = useCallback(<span class="hljs-function">() =&gt;</span> { 
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Tested"</span>);
  }, [a, b, c]);
</code></pre>
<h2 id="heading-usememo-hook">UseMemo hook</h2>
<p><strong>useMemo</strong> is a hook very similar to useCallback. But instead of caching a function, useMemo will cache the <strong>return value of a function</strong>.</p>
<p>In this example, <code>useMemo</code> will cache the number <code>2</code>.</p>
<pre><code class="lang-plaintext">const num = 1
const answer = useMemo(() =&gt; num + 1, [num])
</code></pre>
<p>While <code>useCallback</code> will cache <code>() =&gt; num + 1</code>.</p>
<pre><code class="lang-plaintext">const num = 1
const answer = useMemo(() =&gt; num + 1, [num])
</code></pre>
<h1 id="heading-custom-react-hooks">Custom React Hooks</h1>
<p>If you think about it, hooks are just functions that allow us to implement commonly used logic in our components.</p>
<p>Following this same train of thought, in React apps it's common practice to extract frequently used functionalities into functions and export the with a name starting with the prefix <code>use</code>. This is what we call a custom hook.</p>
<p>Let's see an example of a custom hook that returns us the current window size when we call it.</p>
<pre><code class="lang-plaintext">// Hook
const useWindowSize = () =&gt; {
  // Initialize state with undefined width/height
  const [windowSize, setWindowSize] = useState({
    width: undefined,
    height: undefined,
  });

// Handler to call on window resize
  const handleResize = () =&gt; {
    // Set window width/height to state
    setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
  }

  useEffect(() =&gt; {
    // Add event listener
    window.addEventListener("resize", handleResize);
    // Call handler right away so state gets updated with initial window size
    handleResize();
    // Remove event listener on cleanup
    return () =&gt; window.removeEventListener("resize", handleResize);
  }, []); // Empty array ensures that effect is only run on mount

  return windowSize;
}

export default useWindowSize;
</code></pre>
<p>After, we can call and use our custom hook in any component in the following way:</p>
<pre><code class="lang-plaintext">// Usage
function App() {
  const size = useWindowSize();
  return (
    &lt;div&gt;
      {size.width}px / {size.height}px
    &lt;/div&gt;
  );
}
</code></pre>
<p>As you can see in the example, custom hooks can also use React's native hooks within them. But think about them as just functions that execute certain commonly used logic needed in various parts of our app, It's nothing more complex than that, really.</p>
<p>If you'd like to know more about custom hooks, <a target="_blank" href="https://usehooks.com/">here's a website dedicated exclusively to that topic</a>.</p>
<h1 id="heading-round-up">Round Up</h1>
<p>Well everyone, in this article we've taken a look at hooks, a core topic in current React apps. As always, I hope you enjoyed the article and learned something new.</p>
<p>If you want, you can also follow me on <a target="_blank" href="https://www.linkedin.com/in/germancocca/">LinkedIn</a> or <a target="_blank" href="https://twitter.com/CoccaGerman">Twitter</a>. See you in the next one!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/kobe-bryant-mamba-out.gif" alt="Image" width="600" height="400" loading="lazy"></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Better React Performance – When to Use the useCallback vs useMemo Hook ]]>
                </title>
                <description>
                    <![CDATA[ By Daniel Asta We all want to build powerful applications and avoid unnecessary renders. There are some hooks available to help with this, but you might not be sure about which one to use and when.  In this article you will learn the differences betw... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/better-react-performance-usecallback-vs-usememo/</link>
                <guid isPermaLink="false">66d45e01b6b7f664236cbdb2</guid>
                
                    <category>
                        <![CDATA[ performance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ react hooks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ web performance ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 05 Dec 2022 18:47:25 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/12/useCallback-vs-useMemo.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Daniel Asta</p>
<p>We all want to build powerful applications and avoid unnecessary renders. There are some hooks available to help with this, but you might not be sure about which one to use and when. </p>
<p>In this article you will learn the differences between <code>useCallback</code> and <code>useMemo</code> as well as how to measure the gain of the improvements you're getting in the codebase.</p>
<p>Before we begin, you should note that the following methods for optimising React are really last resort options. Before you apply these utilities, your own code will offer you more opportunities for improvement than most of the performance gain you'll get by using what you will learn here. </p>
<p>Still, it's important to know these tools and know when to use them if you see the opportunity.</p>
<h2 id="heading-resources-youll-need-to-follow-along">Resources You'll Need to Follow Along</h2>
<ul>
<li>Official Beta Documentation for <a target="_blank" href="https://beta.reactjs.org/apis/react/useCallback">useCallback</a> and <a target="_blank" href="https://beta.reactjs.org/apis/react/useMemo">useMemo</a></li>
<li><a target="_blank" href="https://github.com/dastasoft/optimizing-react">Example Project Source Code</a></li>
<li><a target="_blank" href="https://react-optimisation.dastasoft.com/">Example Project Live Demo</a></li>
</ul>
<p>As always, I've provided a sample project so that you can test in a simplified environment everything that is explained here. No big deal, the example project is just a summary of the main points you will learn now.</p>
<p>Before we start comparing these two hooks, let's review some necessary background concepts.</p>
<h2 id="heading-what-is-referential-equality">What is Referential Equality?</h2>
<p>When React compares the values used in a dependency array such as <code>useEffect</code>, <code>useCallback</code>, or props passed to a child component, it uses <code>Object.is()</code>.</p>
<p>You can find the detailed explanation of <a target="_blank" href="http://Object.is">Object.is here</a> but in short:</p>
<ul>
<li>Primitive values are equal (check the link above for the few exceptions).</li>
<li>Non-primitive values refer to the same object in memory.</li>
</ul>
<p>In a simplified example:</p>
<pre><code class="lang-ts"><span class="hljs-string">"string"</span> === <span class="hljs-string">"string"</span> <span class="hljs-comment">// true</span>
<span class="hljs-number">0</span> === <span class="hljs-number">0</span> <span class="hljs-comment">// true</span>
<span class="hljs-literal">true</span> === <span class="hljs-literal">true</span> <span class="hljs-comment">// true</span>
{} === {} <span class="hljs-comment">// false</span>
[] === [] <span class="hljs-comment">// false</span>

<span class="hljs-keyword">const</span> f = <span class="hljs-function">() =&gt;</span> <span class="hljs-string">'Hi'</span>
<span class="hljs-keyword">const</span> f1 = f
<span class="hljs-keyword">const</span> f2 = f

f1 === f1 <span class="hljs-comment">// true</span>
f1 === f2 <span class="hljs-comment">// false</span>
</code></pre>
<h2 id="heading-how-reactmemo-works">How React.memo Works</h2>
<p>Now I'll briefly explain how <code>React.memo</code> works (but we'll also discuss it later in the article). When appropriate, you can use it to improve performance.</p>
<p>When you want to avoid unnecessary re-renders on a child component (even if the parent component changes), you can wrap the whole component with <code>React.memo</code> – as long as the props do not change. Also, <strong>note referential equality here</strong> – the child component will not be re-rendered.</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { memo } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> ChildComponent = <span class="hljs-function">(<span class="hljs-params">props</span>) =&gt;</span> {
  <span class="hljs-comment">// ...</span>
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> memo(ChildComponent)
</code></pre>
<p>Now that you know how <code>React.memo</code> works, let's start.</p>
<h2 id="heading-how-the-usecallback-hook-works">How the useCallback Hook Works</h2>
<p><code>useCallback</code> is one of the built-in hooks we can use to optimise our code. But as you'll see it's not really a hook for direct performance reasons. </p>
<p>In short, <code>useCallback</code> will allow you to save the <em>function definition</em> between component renders.</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { useCallback } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>

<span class="hljs-keyword">const</span> params = useCallback(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-comment">// ...</span>
    <span class="hljs-keyword">return</span> breed
  }, [breed])
</code></pre>
<p>The usage is pretty straightforward:</p>
<ul>
<li>Import <code>useCallback</code> from React because it is a built-in hook.</li>
<li>Wrap a function for which you want to save the definition.</li>
<li>As in <code>useEffect</code>, pass in an array of dependencies that will tell React when this stored value (the function definition in this case) needs to be refreshed.</li>
</ul>
<p>One of the first things to note is precisely the <em>function definition</em> part. It stores the definition, not the execution itself, not the result – so the function will be executed every time it is called. Because of this, don't use this hook to avoid lengthy calculations.</p>
<p>So what is the advantage of storing a function definition?</p>
<h3 id="heading-back-to-referential-equality">Back to Referential Equality</h3>
<p>If the function itself is used, not the returned value, such as:</p>
<ul>
<li>Dependency on <code>useEffect</code> or any other hook.</li>
<li>Prop of a child component, context, and so on.</li>
</ul>
<p>To achieve true equality between renders, <code>useCallback</code> will store the function definition with the <strong>same reference to the object in memory</strong>. </p>
<p>Without this hook, in each render the function will be recreated and point to a different in-memory reference. So React will understand that it is different even if you use <code>React.memo</code> in your child component.</p>
<p>You can test this behaviour in the example project. You'll see that, with the non-optimised version, every time you write the side effect of a child component is triggered. </p>
<p>In that demo, you only get a fetch and a fake slowdown. But imagine this same problem in a large project that runs expensive computations on the client or spends a lot on the server.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/12/use-callback-referential-equality.png" alt="use-callback-referential-equality" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-the-usememo-hook-works">How the <code>useMemo</code> Hook Works</h2>
<p>This is the second built-in hook you will see today. In this case you can consider this hook as a direct optimisation because it stores the result of a function and prevents it from being executed again until the dependencies change.</p>
<p>As it can store the result of a function and also prevent execution between renders of a component, you can use this hook in two situations.</p>
<h3 id="heading-referential-equality">Referential Equality</h3>
<p>As you saw with <code>useCallback</code> we can achieve referential equality with this hook as well – but this time for the result itself. </p>
<p>If a function returns something that is going to be treated differently in each render, most commonly objects and arrays, you can use <code>useMemo</code> to get true equality.</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { useMemo } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>

<span class="hljs-keyword">const</span> params = useMemo(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-comment">// ...</span>
    <span class="hljs-keyword">return</span> { breed }
  }, [breed])
</code></pre>
<p>In the example above you can see the use of <code>useMemo</code>:</p>
<ul>
<li>Import <code>useMemo</code> from React because it is a built-in hook.</li>
<li>Wrap a function for which you want to save the result.</li>
<li>As in <code>useEffect</code>, it passes an array of dependencies that will tell React when this stored value (the value returned by the function) needs to be refreshed.</li>
</ul>
<p>In this case, the function returns an object. As you know, comparing objects with <a target="_blank" href="http://Object.is">Object.is</a> are not the same because they are stored in different memory addresses. With useMemo you can save the same reference.</p>
<p>In the example project you can test this behaviour as in the previous section, same results too. With the non-optimised version, each keystroke will retrieve the images. With <code>useMemo</code>, the equality is maintained and the child component does not retrieve the image again.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/12/use-memo-referential-equality.png" alt="use-memo-referential-equality" width="600" height="400" loading="lazy"></p>
<h3 id="heading-expensive-calculation">Expensive Calculation</h3>
<p>Because you are storing a value and avoiding executing the function at all with <code>useMemo</code>, you can use this to avoid executing unnecessary expensive calculations and make your site more performant.</p>
<p>Let's see this with the example project:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/12/use-memo-expensive-calculation.png" alt="use-memo-expensive-calculation" width="600" height="400" loading="lazy"></p>
<p>There is a component which, given a number n, prints out the nth Fibonacci number. But this recursive version of the algorithm performs rather poorly. </p>
<p>You will also find a constant change over time to force renders. The performance gauge will change state (adding and removing blocks 60 times per second). Because this state is changing all the time, the function that calculates the fibonacci number is constantly running over and over again, even if the given number is always the same.</p>
<p>With this, you will see how the performance degrades visibly when you use higher values with the non-optimised version. The optimised version will only suffer performance spikes when you change the numbers in the slider (when the number changes) but the rest of the renders will skip the calculation and directly serve the result.</p>
<p>The problem here is that in our day to day work we will not encounter calculations called "expensive calculation" and the decision of when to use <code>useMemo</code> won't necessarily be always or never.</p>
<h2 id="heading-when-to-optimise">When to Optimise</h2>
<p>So far you have seen some indicators of when to use the different hooks to avoid unnecessary rendering and/or side effects. But let's define some general rules for deciding when to use them in those not-so-clear cases:</p>
<ul>
<li>Review your code first and rethink how you've structured things. You'll find the biggest opportunities to improve performance in your code itself. You can find more information in <a target="_blank" href="https://overreacted.io/before-you-memo/">this post by Dan Abramov</a>.</li>
<li>If you don't have proof that an optimisation is giving you beneficial results, don't optimise – it's not free.</li>
<li>If you don't want to do the extra work involved in proving that an optimisation is giving you beneficial results, let's be honest: you don't want to optimise either.</li>
</ul>
<h2 id="heading-how-to-measure-performance-impactgain">How to Measure Performance Impact/Gain</h2>
<p>The most important rule for optimisation (that always comes after reviewing your own code first) is to be able to measure whether the changes are taking effect and what the % gain is. And you don't do this only so you can throw that % in your next performance review.</p>
<p>For this we are going to look at two options on how to proceed when you suspect there is a performance problem or simply want to check the main areas of improvement.</p>
<h3 id="heading-clunky-version">Clunky version</h3>
<p>I'll add this option because let's face it: you keep debugging your code with <code>console.log</code> all over the place, don't you? Don't worry, we are in the same boat.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/12/crappy-debugger-meme.png" alt="crappy-debugger-meme" width="600" height="400" loading="lazy"></p>
<p>A fast and furious approach to trying to measure performance problems is to find out how long it takes to execute a certain action and how many times that action is performed. So one way to do this is:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">const</span> t0 = performance.now()
expensiveCalculation(targetNumber)
<span class="hljs-keyword">const</span> t1 = performance.now()
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Call to expensiveCalculation took <span class="hljs-subst">${t1 - t0}</span> milliseconds.`</span>)
<span class="hljs-built_in">console</span>.count(<span class="hljs-string">'Expensive Calculation'</span>)
</code></pre>
<p>But this information alone will detect very few and obvious cases where you already suspected something was wrong. </p>
<p>Also be careful with <code>StrictMode</code> which will trick your <code>console.count</code> by repeating some renders for stability reasons.</p>
<p>Let's now check out the right way to do it.</p>
<h3 id="heading-pro-version">Pro version</h3>
<p>In this version you will use the official <a target="_blank" href="https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi">React Developer Tools</a> to inspect the performance of certain parts of your code. Once you've installed this browser extension, open the browser's developer tools and search for <code>Profiler</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/12/profiler.png" alt="profiler" width="600" height="400" loading="lazy"></p>
<p>I will give examples with the sample project, but you can do it with your own project and check the results.</p>
<p>If you press the <code>record</code> button and start performing the actions that you think might need some performance tuning, the profiler will save and print a detailed explanation of what has happened there.</p>
<p>For example, in the expensive calculation example project we are going to compare side by side the non-optimised version versus the useMemo version:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/12/profiler-graph.png" alt="profiler-graph" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/12/profiler-graph-detailed.png" alt="profiler-graph-detailed" width="600" height="400" loading="lazy"></p>
<p>I pressed the record button, waited a few seconds and pressed record again to get these results, with both versions. As you can see, as this is a prepared extreme case, the huge improvement between the two is evident.</p>
<p>But let's take a closer look at what appears in the profiler:</p>
<ul>
<li>The grey rows are components that have not been re-rendered so it is nothing to worry about in terms of performance.</li>
<li>The green and yellow rows are components that have been re-rendered and you can see how long it took to render.</li>
<li>If you click on each block, you can see a detailed explanation with more data.</li>
</ul>
<p>I will do a full in-depth article on the profiler, but for now here are some quick tips:</p>
<ul>
<li>Under the settings icon, General, check <code>Highlight updates when components render.</code>. This will show what exactly is being rendered and can detect child components that are not meant to render under certain actions.</li>
<li>Under the settings icon, Profiler, check <code>Record why each component rendered while profiling.</code>. This will add a brief explanation of what a component is rendering and that may give you clues as to where you need to place an upgrade.</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>As you have seen, these two common misunderstood hooks have very different functions and scenarios on where to use them for real benefit. Now is the time to review some of your current/past projects and spot the cases where you were using this incorrectly or others that may need it.</p>
<p>Optimisation in React is something that in the future can be done automatically by the library. But, at the time of writing this article, it is a process that you should do with care and after thorough analysis.</p>
<p>I hope you found this tutorial useful and it will help you to build better performing applications with React. Thanks for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Toggle an Element in React using React Hooks ]]>
                </title>
                <description>
                    <![CDATA[ When building a web application, toggling an element is one of the key features you are likely to come across and may need to implement in your project. There are various ways you can toggle an element. In this article, we will take a look at how we ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/toggle-elements-in-react-using-hooks/</link>
                <guid isPermaLink="false">66d45e043dce891ac3a967d0</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ react hooks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ deji adesoga ]]>
                </dc:creator>
                <pubDate>Mon, 07 Nov 2022 18:26:54 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/11/Copy-of-Coffee-Tutorial-YouTube-Thumbnail--1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When building a web application, toggling an element is one of the key features you are likely to come across and may need to implement in your project.</p>
<p>There are various ways you can toggle an element. In this article, we will take a look at how we can implement toggle functionalities in five (5) different ways in React.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-to-install-and-setup-the-react-project">How to Install and Setup the React Project</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-toggle-an-element-using-logical-operators">How to Toggle an Element Using Logical Operators</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-toggle-an-element-using-the-usetoggle-hook">How to Toggle an Element Using the useToggle Hook</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-toggle-an-element-using-the-ternary-operator">How to Toggle an Element Using the Ternary Operator</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-toggle-an-element-using-the-ifelse-statement">How to Toggle an Element Using the If/Else Statement</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-toggle-an-element-using-css-conditional-styling">How to Toggle an Element Using CSS Conditional Styling</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<p>You can also watch the video version of this article below, or on my <a target="_blank" href="https://www.youtube.com/watch?v=S_mgSHCWCmA&amp;t=15s">YouTube channel</a>:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/5CTFTDpHHto" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<h2 id="heading-how-to-install-and-setup-the-react-project">How to Install and Setup the React Project</h2>
<p>To create a React project, you need to have access to NPM (Node Package Manager). Access to NPM requires that you have Node.js installed. You can install Node by heading to the <a target="_blank" href="https://nodejs.org/en/">official Node.js</a> website and downloading Node.js.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/npm-3.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Node.js official documentation</em></p>
<p>I advise selecting the "Recommended For Most Users" version. Once the installation is complete, you can open your terminal and run the commands <code>node -v</code> and <code>npm -v</code>. This gives you details on the version of Node and npm you have.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/terminal-2-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Terminal showing node and npm versions</em></p>
<p>Still in your terminal, you can now install <a target="_blank" href="https://create-react-app.dev/">Create React App</a> which is a platform that allows you to create a React project using the command below:</p>
<p><code>npm i create-react-app</code></p>
<p>The next step is to create a new React project from the terminal by running the command:</p>
<pre><code class="lang-php">npm init react-app toggle
cd toggle 
code .
</code></pre>
<p>Above, we created a new project called <code>toggle</code>. Then we navigated into the newly created project directory and opened the project in our code editor. We can now begin the process of implementing the different methods of toggling an element.</p>
<h2 id="heading-how-to-toggle-an-element-using-logical-operators">How to Toggle an Element Using Logical Operators</h2>
<p>To make sure the design of our page looks structured, we are going to set up Bootstrap 5 inside of the React project.</p>
<p>To do this, head to the <a target="_blank" href="https://getbootstrap.com/docs/5.0/getting-started/introduction/">Bootstrap 5</a> website and copy the CSS CDN link tag. Then go to your <code>index.html</code> file in your React project which can be found in the <code>public</code> directory. Paste the CDN link in the head section, you can see in the code below:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"utf-8"</span> /&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"icon"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"%PUBLIC_URL%/favicon.ico"</span> /&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1"</span> /&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"theme-color"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"#000000"</span> /&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"description"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"Web site created using create-react-app"</span> /&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"apple-touch-icon"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"%PUBLIC_URL%/logo192.png"</span> /&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"manifest"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"%PUBLIC_URL%/manifest.json"</span> /&gt;</span>
  <span class="hljs-comment">&lt;!-- Bootstrap 5 CDN Link --&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span>
    <span class="hljs-attr">integrity</span>=<span class="hljs-string">"sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"</span> <span class="hljs-attr">crossorigin</span>=<span class="hljs-string">"anonymous"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>React App<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">noscript</span>&gt;</span>You need to enable JavaScript to run this app.<span class="hljs-tag">&lt;/<span class="hljs-name">noscript</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"root"</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">body</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Next, create a new folder called <code>components</code> inside of the <code>src</code> directory. Then create a new file called <code>LogicalNot.js</code> inside the <code>components</code> folder. To implement the <strong>logical not</strong> operator method, we'll implement the code below:</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> LogicalNot = <span class="hljs-function">() =&gt;</span> {

  <span class="hljs-comment">//Using Inline Function and the The Logical Not (!) to toggle state</span>
  <span class="hljs-keyword">const</span> [toggle, setToggle] = useState(<span class="hljs-literal">true</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">button</span> 
            <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setToggle(!toggle)} 
            class="btn btn-primary mb-5"&gt;
          Toggle State
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      {toggle &amp;&amp; (
        <span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"list-group"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"list-group-item"</span>&gt;</span>An item<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">class</span>=<span class="hljs-string">"list-group-item"</span>&gt;</span>A second item<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">class</span>=<span class="hljs-string">"list-group-item"</span>&gt;</span>A third item<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">class</span>=<span class="hljs-string">"list-group-item"</span>&gt;</span>A fourth item<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">class</span>=<span class="hljs-string">"list-group-item"</span>&gt;</span>And a fifth one<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;/&gt;</span></span>
  )
}
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> LogicalNot
</code></pre>
<p>Inside of the <code>LogicalNot.js</code> file, we start off by:</p>
<ul>
<li><p>Importing the <code>useState</code> hook.</p>
</li>
<li><p>Then we create two variables called <code>toggle</code> and <code>setToggle</code>, while setting the initial state to <strong>true</strong>.</p>
</li>
<li><p>Next, inside of the <em>jsx</em> section, we create a button that has an <code>onClick</code> event handler. Within this <code>onClick</code> handler, we create an anonymous function by using the setter we declared earlier called <code>setToggle</code>. We then set the argument in the anonymous function to <code>!toggle</code> which creates a false effect when it's clicked.</p>
</li>
<li><p>Finally, we toggle the element in the <code>ul</code> tag by wrapping it around the <code>toggle</code> variable and then rendering it conditionally on the page using the logical <code>&amp;&amp;</code> Operator.</p>
</li>
</ul>
<p>To display the <code>LogicalNot.js</code> file on the browser, head to the <code>App.js</code> file and import the file there as seen below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> <span class="hljs-string">'./App.css'</span>;
<span class="hljs-keyword">import</span> LogicalNot <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/LogicalNot'</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">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App mt-5"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">LogicalNot</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>With that, you should have the result below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/logicanot_2.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Logical not operator sample</em></p>
<h2 id="heading-how-to-toggle-an-element-using-the-usetoggle-hook">How to Toggle an Element Using the useToggle Hook</h2>
<p>You'll start this step by creating a new file called <code>ToggleHook.js</code> inside the <em>components</em> folder. Inside this file, import the <code>useState</code> hook.</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>
</code></pre>
<p>Next, create a variable called <code>useToggle</code> which will hold the logic for the <code>useToggle</code> hook as you can se below:</p>
<pre><code class="lang-javascript">  <span class="hljs-comment">//Using useToggle Hook</span>

  <span class="hljs-keyword">const</span> useToggle = <span class="hljs-function">(<span class="hljs-params">initialState</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> [toggleValue, setToggleValue] = useState(initialState);

    <span class="hljs-keyword">const</span> toggler = <span class="hljs-function">() =&gt;</span> { setToggleValue(!toggleValue) };
    <span class="hljs-keyword">return</span> [toggleValue, toggler]
  };
</code></pre>
<ul>
<li><p>Above, we created a callback function and then gave it a parameter called <code>initialState</code>.</p>
</li>
<li><p>Next, we used the <code>useState</code> hook to create a getter and a setter called <code>toggleValue</code> and <code>setToggleValue</code>, respectively. The <code>useState</code> hook takes the <code>initialState</code> parameter we created earlier which sets the initial value as false by default.</p>
</li>
<li><p>Finally we then created a variable called <code>toggler</code>. This variable holds an anonymous function that contains our <code>useState</code> variables and then sets the results to the opposite value when clicked. We then returned both the <code>toggleValue</code> and <code>toggler</code> variables in an array.</p>
</li>
</ul>
<p>With this we can now use the <code>useToggle</code> hook to create a getter and a setter variable as you can see below:</p>
<pre><code class="lang-jsx">  <span class="hljs-keyword">const</span> [toggle, setToggle] = useToggle();
</code></pre>
<p>We can now implement the logic of the <code>useToggle</code> hook in the <code>jsx</code> part of our code:</p>
<pre><code class="lang-html">    return (
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> 
            <span class="hljs-attr">onClick</span>=<span class="hljs-string">{setToggle}</span> 
            <span class="hljs-attr">class</span>=<span class="hljs-string">"btn btn-secondary mb-5"</span>&gt;</span>
          Toggle State
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>

      {toggle &amp;&amp; (
        <span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"list-group"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"list-group-item"</span>&gt;</span>An item<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">class</span>=<span class="hljs-string">"list-group-item"</span>&gt;</span>A second item<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">class</span>=<span class="hljs-string">"list-group-item"</span>&gt;</span>A third item<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">class</span>=<span class="hljs-string">"list-group-item"</span>&gt;</span>A fourth item<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">class</span>=<span class="hljs-string">"list-group-item"</span>&gt;</span>And a fifth one<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">div</span>&gt;</span>
  )
</code></pre>
<ul>
<li><p>Above, we created a button that contains an <code>onClick</code> event handler using the <code>setToggle</code> setter previously declared above.</p>
</li>
<li><p>Then we rendered the elements based on the boolean condition of the <code>toggle</code> variable when it gets clicked.</p>
</li>
</ul>
<p>With that, we should have the result below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/useToggle.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>useToggle sample</em></p>
<h2 id="heading-how-to-toggle-an-element-using-the-ternary-operator">How to Toggle an Element Using the Ternary Operator</h2>
<p>The ternary operator is a JavaScript operator that takes in three different operations, which are:</p>
<ul>
<li><p>A condition</p>
</li>
<li><p>A question mark (?) to execute a condition if true</p>
</li>
<li><p>A colon (:) to execute a condition if false</p>
</li>
</ul>
<p>To implement this method, you'll start by importing the <code>useState</code> hook:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
</code></pre>
<p>Then you need to create two variables using the <code>useState</code> hook and setting the default value to true:</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">const</span> [toggle, setToggle] = useState(<span class="hljs-literal">true</span>);
</code></pre>
<p>Next, create a variable called <code>handleClick</code> that holds a callback function. Within this function, call the <code>setToggle</code> setter and then pass in <code>!toggle</code> to return an opposite value when clicked, as you can see below:</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">const</span> handleClick = <span class="hljs-function">() =&gt;</span> {
    setToggle(!toggle);
  };
</code></pre>
<p>Finally, you can now render the logic of the variables you created in your <code>jsx</code>:</p>
<pre><code class="lang-javascript">  <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">button</span> 
      <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleClick}</span> 
      <span class="hljs-attr">class</span>=<span class="hljs-string">"btn btn-info mb-5"</span>&gt;</span>
      Toggle State
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>

      {toggle ?
        <span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"list-group"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"list-group-item"</span>&gt;</span>An item<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">class</span>=<span class="hljs-string">"list-group-item"</span>&gt;</span>A second item<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">class</span>=<span class="hljs-string">"list-group-item"</span>&gt;</span>A third item<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">class</span>=<span class="hljs-string">"list-group-item"</span>&gt;</span>A fourth item<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">class</span>=<span class="hljs-string">"list-group-item"</span>&gt;</span>And a fifth one<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;&gt;</span><span class="hljs-tag">&lt;/&gt;</span></span>
      }
    &lt;/div&gt;
  )
</code></pre>
<ul>
<li><p>Above we created a button that uses an <code>onClick</code> event handler to reference the <code>handleClick</code> variable we created earlier.</p>
</li>
<li><p>Then we can render the elements by using the <code>toogle</code> variable condition, as well as the question mark (?) which displays elements if the <code>toggle</code> variable is set to true, or displays an empty <em>jsx</em> fragment by using the colon (:) if the toggle variable is set to false.</p>
</li>
</ul>
<p>With that, we should have the result below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/ternary.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Ternary operator sample</em></p>
<h2 id="heading-how-to-toggle-an-element-using-the-ifelse-statement">How to Toggle an Element Using the If/Else Statement</h2>
<p>The <code>If/Else</code> statement is a conditional statement used to perform different actions based on certain parameters. The <code>if</code> statement executes a certain condition if it is true, and the <code>else</code> statement executes when the condition is false.</p>
<p>To see the if/else statement in action, let's begin by importing the <code>useState</code> hook:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
</code></pre>
<p>Next, create the getter and setter variables and then set the default value to true:</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">const</span> [toggle, setToggle] = useState(<span class="hljs-literal">true</span>);
</code></pre>
<p>Next, create a variable called <code>handleClick</code> that holds the callback function. Within this function, call the <code>setToggle</code> setter and then pass in <code>!toggle</code> to return an opposite value when clicked, as you can see below:</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">const</span> handleClick = <span class="hljs-function">() =&gt;</span> {
    setToggle(!toggle)
  };
</code></pre>
<p>You can now display the elements by using the <code>toggle</code> getter in the <code>jsx</code> as you can see below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (toggle) {
    <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">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleClick}</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn btn-dark mb-5"</span>&gt;</span>Toggle State<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"list-group"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"list-group-item"</span>&gt;</span>An item<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">class</span>=<span class="hljs-string">"list-group-item"</span>&gt;</span>A second item<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">class</span>=<span class="hljs-string">"list-group-item"</span>&gt;</span>A third item<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">class</span>=<span class="hljs-string">"list-group-item"</span>&gt;</span>A fourth item<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">class</span>=<span class="hljs-string">"list-group-item"</span>&gt;</span>And a fifth one<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">div</span>&gt;</span></span>
    )
  } <span class="hljs-keyword">else</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">onClick</span>=<span class="hljs-string">{handleClick}</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn btn-dark mb-5"</span>&gt;</span>Toggle State<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
  }
</code></pre>
<ul>
<li><p>In the <code>jsx</code>, we wrapped the entire element around the <code>if/else</code> statement.</p>
</li>
<li><p>Within the <code>if</code> statement, we rendered the elements that contain the list items on the page when the <code>toggle</code> is set as true.</p>
</li>
<li><p>In the else block, however, when the toggle is set to false, only the button element gets returned.</p>
</li>
</ul>
<p>With that, we get the result below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/if-else.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>If/else statement sample</em></p>
<h2 id="heading-how-to-toggle-an-element-using-css-conditional-styling">How to Toggle an Element Using CSS Conditional Styling</h2>
<p>Conditional styling is one of the ways you can use to manipulate DOM elements in React based on a specific condition. As we've done previously, let's start by importing the <code>useState</code> hook in React:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
</code></pre>
<p>Next, set up your <code>useState</code> hook creating the required variables:</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">const</span> [toggle, setToggle] = useState(<span class="hljs-literal">true</span>);
</code></pre>
<p>Then create the function that helps set the value of your opposite state when clicked:</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">const</span> handleClick = <span class="hljs-function">() =&gt;</span> {
    setToggle(!toggle);
  };
</code></pre>
<p>With this you can now configure the conditional styling in the <code>jsx</code> section of your code:</p>
<pre><code class="lang-javascript"> <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">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleClick}</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn btn-warning mb-5"</span>&gt;</span>Toggle State<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>

      <span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"list-group"</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">display:</span> <span class="hljs-attr">toggle</span> ? '<span class="hljs-attr">block</span>' <span class="hljs-attr">:</span> '<span class="hljs-attr">none</span>' }}&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"list-group-item"</span>&gt;</span>An item<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">class</span>=<span class="hljs-string">"list-group-item"</span>&gt;</span>A second item<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">class</span>=<span class="hljs-string">"list-group-item"</span>&gt;</span>A third item<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">class</span>=<span class="hljs-string">"list-group-item"</span>&gt;</span>A fourth item<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">class</span>=<span class="hljs-string">"list-group-item"</span>&gt;</span>And a fifth one<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">div</span>&gt;</span></span>
  )
</code></pre>
<ul>
<li><p>Above, we started by creating the button that contains the <code>onClick</code> event handler called <code>handleClick</code> as created earlier.</p>
</li>
<li><p>Then we used the style attribute in the <code>ul</code> tag to conditionally set the display to block when the <code>toggle</code> variable is true. If the <code>toggle</code> variable is false, we set the display to none. This is possible through the ternary operator.</p>
</li>
</ul>
<p>The result looks like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/condition.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Conditional styling sample</em></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, you learned the various ways you can toggle elements in a React application. If you want access to the code base, you can clone the repo <a target="_blank" href="https://github.com/desoga10/showandhide">here</a> on GitHub.</p>
<p>Also, if you enjoyed this article, you can kindly show your support by subscribing to my <a target="_blank" href="https://www.youtube.com/TheCodeAngle">YouTube channel</a> where I create awesome tutorials on web development technologies like Angular, React, JavaScript, Html, CSS, and many more concepts.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ React Hooks for Beginners – Learn to Use the useState Hook in 10 Minutes ]]>
                </title>
                <description>
                    <![CDATA[ By Eduardo Vedes Hey everyone 🌈 I haven't written about handling state in React for a long time. The last time was in this article, four years ago, and it seems like it helped a lot of you. I received tons of views and amazing feedback, so thanks a ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-react-usestate-hook-in-10-minutes/</link>
                <guid isPermaLink="false">66d45f03d1ffc3d3eb89dded</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ react hooks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ State Management  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 30 Jun 2022 19:40:11 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/09/philipp-katzenberger-jVx8JaO2Ddc-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Eduardo Vedes</p>
<p>Hey everyone 🌈 I haven't written about handling state in React for a long time. The last time was <a target="_blank" href="https://www.freecodecamp.org/news/get-pro-with-react-setstate-in-10-minutes-d38251d1c781/">in this article</a>, four years ago, and it seems like it helped a lot of you.</p>
<p>I received tons of views and amazing feedback, so thanks a lot – you really rock! 🎸</p>
<p>Well, a lot of time has passed since then. Hooks landed in React since version v16.8 (in 2019) and there's a lot to keep up with when using state in React.</p>
<p>Are you learning about state and want to become a pro with the <strong>useState</strong> hook? </p>
<p>Cool, you've came to the right place! Grab a coffee (or tea), fasten your seatbelts, and let's go!</p>
<p>By the way – if you're looking for how to use setState (in class components), then I recommend that you check out my former article <a target="_blank" href="https://www.freecodecamp.org/news/get-pro-with-react-setstate-in-10-minutes-d38251d1c781/">"How to become a pro with React setState() in 10 minutes"</a>. </p>
<h2 id="heading-what-is-a-react-hook">What is a React Hook?</h2>
<p>A hook is a special function that lets you <strong>"hook into"</strong> various React features. Imagine a function that returns an array with two values: </p>
<ul>
<li><strong>The first value:</strong> a variable with the state. </li>
<li><strong>The second value:</strong> a variable with an handler (a function to change the current state). </li>
</ul>
<p>That's it, easy-peasy. 🥞</p>
<p>Remember that in JavaScript <strong>"values are functions, and functions are values"</strong>. I learned this back in 2017 with <a target="_blank" href="https://www.youtube.com/c/funfunfunction"><strong>MPJ</strong></a>, one of my favourite developers and YouTubers. Thanks for everything MPJ!  </p>
<p>In case this confused you a bit, here's an example:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/01.png" alt="Image" width="600" height="400" loading="lazy">
<em>values are functions, and functions are values</em></p>
<p>Let's see what's happening here:</p>
<ul>
<li>In <strong>a</strong>, you store a number. I mean, you assign the value <strong>1</strong> (which is a number) to a variable called <strong>a</strong>. </li>
<li>In <strong>b</strong>, you store the result (value) of evaluating an expression. </li>
<li>In <strong>c</strong> you store a function. You store a non-executed function, which is stored as a value, and ready to be executed anytime. </li>
<li>In <strong>d</strong> we assign the result of evaluating <strong>c</strong>. </li>
</ul>
<p>Makes sense? Do you get the gist? Yeah, <strong>functions are values, and values are functions</strong>! That's all you need to know about it for now.</p>
<p><strong>useState</strong>, in particular, lets you add React state to functional components (components that are declared as a function, and not as a class). </p>
<p>In truth, state is kept inside the hook, but is accessible from the component where you "call" the hook.</p>
<h2 id="heading-the-rules-of-react-hooks">The Rules of React Hooks</h2>
<p>Besides the fact that Hooks are JavaScript functions, there are some rules to follow while using them:</p>
<h3 id="heading-only-call-hooks-at-the-top-level">Only Call Hooks at the Top Level</h3>
<p>Don't call hooks inside loops, conditions, or nested functions. Always use hooks at the top level of your React function (component), before any early returns.</p>
<p>The reason behind this is that hooks must be called in the same order each time a component renders. This is what allows React to correctly preserve the state of hooks between multiple useState and useEffect calls.</p>
<h4 id="heading-only-call-hooks-from-react-functions">Only Call Hooks from React Functions</h4>
<p>This means you can call hooks from React functions (components) or from custom hooks, but not from regular JavaScript functions.</p>
<p>There's this useful plugin <a target="_blank" href="https://www.npmjs.com/package/eslint-plugin-react-hooks">here</a> that enforces the rules of hooks. It's a very helpful one so make sure you try it out.</p>
<h2 id="heading-the-anatomy-of-the-usestate-hook">The Anatomy of the useState Hook</h2>
<p>To use the useState hook, you need to know a few things.</p>
<p>💡You can check the figure below to better understand what I'll explain here.</p>
<ol>
<li>You must import it from the React library.</li>
<li>You must invoke it inside a React component</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> [state, setState] = useState(initialValue)
</code></pre>
<p>Not sure if you get the destructuring, so for those who didn't catch it at first glance:</p>
<p>I could do something like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> array = useState(initialValue)
</code></pre>
<p>And then I could use the state, inside position 0, as array[0], and the handler to setState, inside position 1, as array[1].</p>
<p>It happens to be much more declarative to destructure the array, as we know its first and second position values, and we know they correspond to the state value and to a handler to change it.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> [first, second] = useState(initialValue)
</code></pre>
<p>Yeah, we could to this. But we can call anything to first and second. The only rule is that these variables correspond to the first and second positions of the array returned by the <strong>useState</strong> function (hook).</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> [state, setState] = useState(initialValue)
<span class="hljs-keyword">const</span> [counter, setCounter] = useState(initialCount)
<span class="hljs-keyword">const</span> [something, setSomething] = useState(initialSomething)
</code></pre>
<p>If you're not familiar with the destructuring assignment syntax, feel free to pause reading and take a sneak peak into <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">MDN</a> or <a target="_blank" href="https://www.freecodecamp.org/news/destructuring-patterns-javascript-arrays-and-objects/">read this helpful tutorial</a>.</p>
<p>Go ahead – I'll wait! (<em>Edo sips a bit of</em> ☕)</p>
<ol start="3">
<li>You can then freely render state, or call setState to update your state value.</li>
</ol>
<p>And here's the simplest fully functional example you can have:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/carbon.png" alt="Image" width="600" height="400" loading="lazy">
<em>The Anatomy of the useState hook</em></p>
<h2 id="heading-when-to-use-the-usestate-hook">When to Use the useState Hook</h2>
<p>To understand when to use this hook, we need to start by learning when we need state.</p>
<p>At first glance, we think that when we need a variable that changes over time, we need to keep it in state. But this is not true, most of the time. I mean, if your variable can be derived from other data, then you don't need state.</p>
<h3 id="heading-state-example-1">State Example 1:</h3>
<p>A theme color, that can be light or dark, according to the hour, can be derived from system data.</p>
<p>We can simply get the time (date) from the JS Date function. So we don't need state here, right? This is a const you can declare with an expression or function that must be evaluated.</p>
<h3 id="heading-state-example-2">State Example 2:</h3>
<p>A modal toggle (to show/hide a modal).</p>
<p>Modal toggle can be true or false, and it's triggered when the user clicks a button. So, in this case we really need state, because we can't derive this kind of information – it only depends on "when and if" the user triggers the event or not.</p>
<p>Be mindful of this difference – between what can be derived and what depends on the user.</p>
<p>You'll want to use the <strong>useState</strong> hook when you need to store input from a user.</p>
<p>💡As a rule of thumb, you should only use state to keep this kind of information – that requires the user to input data, or trigger events.</p>
<p>Another very used example is <strong>form</strong> data. Almost every app or website needs to collect info from the user. And to do that it's pretty usual (or mandatory) to have a form.</p>
<p>Form data must be stored in state, at least until it's persisted to a database. But it can also be retrieved from a database, and made editable again.</p>
<p>Cool, let's continue.</p>
<h2 id="heading-how-to-use-multiple-state-variables-in-react">How to Use Multiple State Variables in React</h2>
<p>So, if we need to handle multiple states, the best and recommended first approach is to handle them separately, like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/carbon--1-.png" alt="Image" width="600" height="400" loading="lazy">
<em>Dogs and Cats Counter (Handling Multiple State Variables)</em></p>
<p>There's nothing wrong with doing this, in spite of the fact that it seems to be primitive. It's a good and linear approach as we keep working with JavaScript primitives (in this case numbers).</p>
<p>You can also mix state in one object:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/carbon--2-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This case becomes a bit more complex. We've initialized an object, instead of a primitive value. When we call setPets, we must be aware that we need to spread the existing pets object, and then add the change, otherwise we'll lose it. </p>
<p>With the old setState API this wasn't mandatory – it would understand that you wanted to update a key of the state object. But nowadays it doesn't, and I like it. Now it's more declarative and more of a fundamental concept in JavaScript.</p>
<p>If by any chance you're not familiar with the spread syntax, feel free to check it out <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">here</a> or <a target="_blank" href="https://www.freecodecamp.org/news/javascript-object-destructuring-spread-operator-rest-parameter/">read this helpful tutorial</a>.</p>
<h2 id="heading-state-asynchrony">State Asynchrony</h2>
<p>Beware that changing / mutating state is an asynchronous operation.</p>
<p>Let's see an evidence:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/carbon--3-.png" alt="Image" width="600" height="400" loading="lazy">
<em>State is asynchronous (it's batched and updated with a delay)</em></p>
<p>So, I've updated our initial dogs example a bit. This time I've created a <strong>handleDogsCount</strong> function to show it to you.</p>
<p>Inside the handleDogsCount I call <strong>setDogs</strong> with the new value.</p>
<p>What happens if I need to use the state value immediately for another operation?</p>
<p>Right, the state wasn't updated yet. The best way to approach an immediate operation is to use the value passed to the handleDogsCount function, and – forgetting the dogs state value for now – knowing before hand (this is tricky, but it is what it is) that the value wasn't updated on time.</p>
<h2 id="heading-how-to-mutate-state-in-a-functional-way">How to Mutate State in a Functional Way</h2>
<p>Okay, now we know that state doesn't change immediately. And there's another question related to it. What would happen if you could click the More button 1M times per second?</p>
<p>Possibly, at the end of the 1M clicks, the counter would be 999_998 (or less), and not 1_000_000 as expected.</p>
<p>To avoid this happening, we can set state in a functional way. We'd grab the value of the previous state, so that React can properly batch all the requests and update state linearly. This way we wouldn't lose information in the middle.</p>
<p>To do that you could simply do the following:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/carbon--4-.png" alt="Image" width="600" height="400" loading="lazy">
<em>Mutating state in a functional way</em></p>
<p>Okay, cool. Now we're sure React won't miss a thing while handling our 1M requests to mutate state. </p>
<p>Instead of grabbing the dogs variable to add or subtract one, we rely on the previousState that is exposed inside the useState setState handler (in this case the setDogs function).</p>
<p>Beware that objects and arrays are compared by reference, so complex state should be tamed properly in the dependency arrays of other hooks, such as, <strong>useEffect</strong>. We'll talk about it later, in another article! </p>
<p>If you're new to JavaScript, let me give you a spoiler about what I'm talking about:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/carbon--5-.png" alt="Image" width="600" height="400" loading="lazy">
<em>Comparison by ref</em></p>
<p>As you see, <strong>c</strong> is not strictly equal to <strong>d</strong>. Yes, go ahead and try it! It happens that JavaScript compares complex objects (all that aren't <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Primitive">primitive</a>) by reference, not by value. </p>
<p>If I stringify it, it means I'm comparing strings. And because they're primitive, they're strictly equal (compared by value).</p>
<h2 id="heading-how-to-initialize-state-as-a-function">How to Initialize State as a Function</h2>
<p>If you need to initialize state with an expensive computation, then it's better to initialize it with a function, and not a value.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> [ dogs, setDogs] = useState(<span class="hljs-function">() =&gt;</span> expensiveComputation())
</code></pre>
<p>This means we're lazily initializing the variable. The initial value will be assigned only on the initial render (again, if it's a function). </p>
<p>In subsequent renders (due to change of state in the component or a parent component), the argument of the useState hook will be ignored and the current value will be retrieved.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>So, it seems we've reached the end of this journey.</p>
<p>You've learned what a hook is, the rules of hooks, how useState works, its anatomy, and how can you handle multiple states.</p>
<p>You've also learned some pitfalls (such as handling state objects, or that state is asynchronous), and some tricks to improve performance, such as initializing state as a function to avoid being constantly evaluating that computation.</p>
<p>Hope you have enjoyed this article about the <strong>useState</strong> hook, or simply the "state hook".</p>
<h2 id="heading-last-but-not-least">Last But Not Least</h2>
<p>I'm <a target="_blank" href="https://eduardovedes.com/">Edo</a>. I'm a freeCodeCamp advocate who enjoys helping people change careers into Software Engineering.</p>
<p>If you're changing careers, or thinking about doing a career change, it might inspire you to read a bit of my <a target="_blank" href="https://www.freecodecamp.org/news/from-civil-engineer-to-web-developer-with-freecodecamp/">story</a>, which was published here on the freeCodeCamp publication.</p>
<p>You might also be interested in <a target="_blank" href="https://www.freecodecamp.org/news/how-to-become-a-junior-software-engineer-in-6-months/">"How to Become a Junior Software Engineer in 6 months"</a>.</p>
<p>If you enjoyed this article, please follow me on <a target="_blank" href="https://twitter.com/eduardovedes">Twitter</a> and just reach out so that we can chat!</p>
<p>Thanks everyone 🌈, you rock!</p>
<p>Edo</p>
<h3 id="heading-for-more-about-react-hooks">For more about React Hooks...</h3>
<ol>
<li><a target="_blank" href="https://reactjs.org/docs/hooks-state.html">React Documentation</a></li>
</ol>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
