<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: ryanharris.dev</title>
    <description>The latest articles on DEV Community by ryanharris.dev (@ryanharris).</description>
    <link>https://dev.to/ryanharris</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F143406%2F4a47c646-73a8-46cb-ae03-11a721d0559e.jpg</url>
      <title>DEV Community: ryanharris.dev</title>
      <link>https://dev.to/ryanharris</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/ryanharris"/>
    <language>en</language>
    <item>
      <title>Using ternaries for variable assignment in Python</title>
      <dc:creator>ryanharris.dev</dc:creator>
      <pubDate>Tue, 25 May 2021 00:14:23 +0000</pubDate>
      <link>https://dev.to/ryanharris/using-ternaries-for-variable-assignment-in-python-34p2</link>
      <guid>https://dev.to/ryanharris/using-ternaries-for-variable-assignment-in-python-34p2</guid>
      <description>&lt;p&gt;One of my favorite "tricks" as a programmer is to condense conditional logic (i.e. &lt;code&gt;if/else&lt;/code&gt; blocks) into one line when assigning variables. The &lt;a href="https://en.wikipedia.org/wiki/Ternary_operation"&gt;ternary operator&lt;/a&gt; makes this possible.&lt;/p&gt;

&lt;p&gt;If you come from a JavaScript background like I do, you may have seen this done before with a question mark.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;isSuccess&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;response&lt;/span&gt; &lt;span class="p"&gt;?&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Essentially, this means if data.response is defined we should assign isSuccess the value of true. Otherwise, we'll set it to false.&lt;/p&gt;

&lt;p&gt;Recently, I used a ternary operation in Python for the first time. While it, ultimately, works the same way I found the slight difference between languages interesting.&lt;/p&gt;

&lt;p&gt;To recreate the snippet above in Python, we could write:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;is_success&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;True&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;response&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="bp"&gt;False&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, the right-side of the assignment leads with the "truthy" value, as opposed to the value we're checking. It's not a big difference, but worth noting the difference in API.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;?&lt;/code&gt; operator has a special place in my heart because I've used it so much. However, Python's ternary operator syntax is probably easier to read for beginners.&lt;/p&gt;

</description>
      <category>python</category>
      <category>programming</category>
      <category>beginners</category>
    </item>
    <item>
      <title>React Hooks Revisited: useDebugValue</title>
      <dc:creator>ryanharris.dev</dc:creator>
      <pubDate>Fri, 18 Sep 2020 12:59:41 +0000</pubDate>
      <link>https://dev.to/ryanharris/react-hooks-revisited-usedebugvalue-53je</link>
      <guid>https://dev.to/ryanharris/react-hooks-revisited-usedebugvalue-53je</guid>
      <description>&lt;h3&gt;
  
  
  #TIL
&lt;/h3&gt;

&lt;p&gt;I'll be honest: before working on this series, I had never heard of &lt;code&gt;useDebugValue&lt;/code&gt; (or seen it in a codebase).&lt;/p&gt;

&lt;p&gt;Unlike the hooks we've covered thus far, &lt;code&gt;useDebugValue&lt;/code&gt; is not intended to add functionality to your applications. Instead, as the name suggests, it is used as a debugging tool and can help developers troubleshoot issues in their custom React hooks.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;We don’t recommend adding debug values to every custom Hook. It’s most valuable for custom Hooks that are part of shared libraries. ~ &lt;a href="https://reactjs.org/docs/hooks-reference.html#usedebugvalue" rel="noopener noreferrer"&gt;React docs&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Though it doesn't effect your application logic in anyway, this hook can negatively effect performance in certain cases if you're not careful (more on this later).&lt;/p&gt;

&lt;h3&gt;
  
  
  Anatomy of useDebugValue
&lt;/h3&gt;

&lt;p&gt;First things first, let's see what &lt;code&gt;useDebugValue&lt;/code&gt; looks like in action:&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://codesandbox.io/embed/hooksusedebugvalue-ccnju"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;In the snippet above, we've defined our own custom hook, &lt;code&gt;useDate&lt;/code&gt; (more about these in an upcoming article). Currently, the hook fires once on &lt;code&gt;App&lt;/code&gt;'s initial render -- due to the empty dependency array -- and displays it on the page.&lt;/p&gt;

&lt;p&gt;Note that we're also using a &lt;code&gt;useDebugValue&lt;/code&gt; hook within &lt;code&gt;useDate&lt;/code&gt;, which takes a single value and then displays it in the &lt;a href="https://github.com/facebook/react-devtools" rel="noopener noreferrer"&gt;React DevTools&lt;/a&gt;. In the screenshot below, you can see how the snippet above would look in your browser.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fryanharris.dev%2Fstatic%2F29c9f2007c8563e6c17f5ba61573cc04%2F1f09d%2F01-debug-value-before-after.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fryanharris.dev%2Fstatic%2F29c9f2007c8563e6c17f5ba61573cc04%2F1f09d%2F01-debug-value-before-after.png" alt="useDebugValue output in React DevTools"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Formatting useDebugValue
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;useDebugValue&lt;/code&gt; also takes an optional second argument, which can be used to format the hook's display value. In this case, the function's signature would look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nf"&gt;useDebugValue&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;date&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;date&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;date&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;toDateString&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="nf"&gt;toUpperCase&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The hook works the same way it does without the second argument, however, it's output now looks like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fryanharris.dev%2Fstatic%2Fdb33076790b111f0ce9bd96d33ba06c9%2Ff96db%2F02-upper-case.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fryanharris.dev%2Fstatic%2Fdb33076790b111f0ce9bd96d33ba06c9%2Ff96db%2F02-upper-case.png" alt="Formatted useDebugValue output in React DevTools"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Notes about the formatting function
&lt;/h3&gt;

&lt;p&gt;As I mentioned in the intro, while this hook does not effect how your application works, it can effect performance if the logic within the formatter function is expensive.&lt;/p&gt;

&lt;p&gt;Luckily, the React team built in a safeguard for this and, &lt;a href="https://reactjs.org/docs/hooks-reference.html#defer-formatting-debug-values" rel="noopener noreferrer"&gt;as it says in the documentation&lt;/a&gt;, the function will only be executed when you are inspecting your hooks within the dev tools.&lt;/p&gt;

&lt;p&gt;Though use-cases for a complex formatter function may be few and far between, be careful about the logic you house within it so as to avoid unintended performance issues.&lt;/p&gt;

&lt;h3&gt;
  
  
  Real-world use case
&lt;/h3&gt;

&lt;p&gt;Odds are you won't be using &lt;code&gt;useDebugValue&lt;/code&gt; too much in your day to day work unless you're building custom hooks or an open source library.&lt;/p&gt;

&lt;p&gt;Since custom hooks are built using the standard hooks provided by React, &lt;code&gt;useDebugValue&lt;/code&gt; is primarily a nice solution to help you debug the internals of your hook implementation in the React Dev Tools pane, as opposed to adding &lt;code&gt;console.log()&lt;/code&gt; calls everywhere.&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>React Hooks Revisited: useReducer</title>
      <dc:creator>ryanharris.dev</dc:creator>
      <pubDate>Thu, 17 Sep 2020 13:11:50 +0000</pubDate>
      <link>https://dev.to/ryanharris/react-hooks-revisited-usereducer-5mo</link>
      <guid>https://dev.to/ryanharris/react-hooks-revisited-usereducer-5mo</guid>
      <description>&lt;h3&gt;
  
  
  An update on state
&lt;/h3&gt;

&lt;p&gt;Throughout this series, all of the code snippets and sandboxes we've created have used &lt;code&gt;useState&lt;/code&gt; to manage our component data. However, React offers us an additional hook to use for storing data: &lt;code&gt;useReducer&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;While &lt;code&gt;useState&lt;/code&gt; allows us to store and set a single value, &lt;code&gt;useReducer&lt;/code&gt; helps us work with more complex or structured data by allowing us to store and manipulate related values alongside one another.&lt;/p&gt;

&lt;h3&gt;
  
  
  Anatomy of useReducer
&lt;/h3&gt;

&lt;p&gt;Like &lt;code&gt;useState&lt;/code&gt;, &lt;code&gt;useReducer&lt;/code&gt; returns an array with two values:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The current state&lt;/li&gt;
&lt;li&gt;A function used to update the state
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;setValue&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;state&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;dispatch&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useReducer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;reducer&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;initialState&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;useReducer&lt;/code&gt; hook takes up to three arguments:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Reducer function&lt;/strong&gt; -- This function describes how our state should be updated based on the action that was dispatched.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Initial state&lt;/strong&gt; -- This value defines the hook's initial state and works similiarly to how we provide the &lt;code&gt;useState&lt;/code&gt; hook a default value when instantiating it.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Initialization function&lt;/strong&gt; -- This argument is optional and is useful for...&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;blockquote&gt;
&lt;p&gt;...calculating the initial state outside the reducer. This is also handy for resetting the state later in response to an action. ~ &lt;a href="https://reactjs.org/docs/hooks-reference.html#lazy-initialization"&gt;React docs&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Difference from useState
&lt;/h3&gt;

&lt;p&gt;To best illustrate the difference in how &lt;code&gt;useReducer&lt;/code&gt; and &lt;code&gt;useState&lt;/code&gt; update their state values, respectively, let's take a look at them side by side. The snippet below shows the code you'd need to use to instantiate and update a state value using both hooks:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// useState&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;setName&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;""&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nx"&gt;setName&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Ryan&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;// 'Ryan'&lt;/span&gt;

&lt;span class="c1"&gt;// useReducer&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;initialState&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;""&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;reducer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;state&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;action&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;switch&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;action&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;type&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;case&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;update-name&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
      &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;action&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="p"&gt;}&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;state&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;dispatch&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useReducer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;reducer&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;initialState&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nx"&gt;dispatch&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;update-name&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;value&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Ryan&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt; &lt;span class="p"&gt;})&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;state&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;// 'Ryan'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first difference here is that while &lt;code&gt;useState&lt;/code&gt; is storing a string, &lt;code&gt;useReducer&lt;/code&gt;'s initial value is an object. In this case, it has a single key (i.e. &lt;code&gt;name&lt;/code&gt;), however, we can always add more keys to the state as we build out our UI.&lt;/p&gt;

&lt;p&gt;Secondly, while &lt;code&gt;useState&lt;/code&gt;'s setter function updates its value directly, &lt;code&gt;useReducer&lt;/code&gt; dispatches an action. The reducer function then determines what type of action was fired and, subsequently, how to update its state.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note:&lt;/em&gt; If you haven't used it in the past, this is pretty much how &lt;a href="https://redux.js.org/"&gt;Redux&lt;/a&gt; works.&lt;/p&gt;

&lt;h3&gt;
  
  
  In practice
&lt;/h3&gt;

&lt;p&gt;In the sandbox below, I've built a form for scheduling an appointment. Though there are multiple inputs with different types, all of the values are related to one another as they are in the same &lt;code&gt;&amp;lt;form&amp;gt;&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://codesandbox.io/embed/hooksusereducer-5rntg"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;Instead of storing each input value in its own &lt;code&gt;useState&lt;/code&gt; hook, we can store and manage all of the values in our form using a single &lt;code&gt;useReducer&lt;/code&gt;. In this case, its state is an object with many keys, each representing a different value we want to store. Personally, this reminds me a bit of &lt;code&gt;this.state&lt;/code&gt; in &lt;code&gt;class&lt;/code&gt; components before we had hooks.&lt;/p&gt;

&lt;p&gt;In &lt;code&gt;App.js&lt;/code&gt;, we've defined our initial state like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;blankForm&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;""&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;email&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;""&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;date&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;""&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;time&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;""&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;feeling&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;3&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;formState&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;dispatch&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useReducer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;reducer&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;blankForm&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each of the fields in the &lt;code&gt;blankForm&lt;/code&gt; object represents and stores the value for an associated input in our form. Since the initial state of &lt;code&gt;email&lt;/code&gt; is an empty string, the e-mail input will be blank on render as it reads its value from &lt;code&gt;useReducer&lt;/code&gt;'s state:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;input&lt;/span&gt;
  &lt;span class="nx"&gt;className&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Form__input&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
  &lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;email&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
  &lt;span class="nx"&gt;type&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;email&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
  &lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;formState&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;email&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="sr"&gt;/&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To make this work, we've also set our inputs' &lt;code&gt;onChange&lt;/code&gt; handlers to dispatch specific actions in order to update the state. Here's what our e-mail input now looks like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;input&lt;/span&gt;
  &lt;span class="nx"&gt;className&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Form__input&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
  &lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;email&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
  &lt;span class="nx"&gt;type&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;email&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
  &lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;formState&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;email&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
  &lt;span class="nx"&gt;onChange&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;dispatch&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;setEmail&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;value&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;target&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt; &lt;span class="p"&gt;})&lt;/span&gt;
  &lt;span class="p"&gt;}}&lt;/span&gt;
&lt;span class="sr"&gt;/&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the snippet above, we're specifically dispatching the &lt;code&gt;setEmail&lt;/code&gt; action. Inside of our reducer function, the &lt;code&gt;switch&lt;/code&gt; statement looks for the &lt;code&gt;case&lt;/code&gt; that matches the &lt;code&gt;action.type&lt;/code&gt; and executes its logic to update state:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;reducer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;state&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;action&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;switch&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;action&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;type&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;case&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;setName&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
      &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="nx"&gt;state&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;action&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;case&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;setEmail&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
      &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="nx"&gt;state&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="na"&gt;email&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;action&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;case&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;setDate&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
      &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="nx"&gt;state&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="na"&gt;date&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;action&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;case&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;setTime&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
      &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="nx"&gt;state&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="na"&gt;time&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;action&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;case&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;setFeeling&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
      &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="nx"&gt;state&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="na"&gt;feeling&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;action&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;case&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;reset&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
      &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;blankForm&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For example, when &lt;code&gt;setEmail&lt;/code&gt; is called the reducer returns a new object that contains all of the current state information, except it &lt;strong&gt;also&lt;/strong&gt; updates the &lt;code&gt;email&lt;/code&gt; field.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="nx"&gt;state&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;email&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;action&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, since our &lt;code&gt;useReducer&lt;/code&gt; hook's state has now been updated, the component will re-render and the &lt;code&gt;&amp;lt;input /&amp;gt;&lt;/code&gt;s all display their updated value from &lt;code&gt;formState&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Notes about performance
&lt;/h3&gt;

&lt;p&gt;As my friend &lt;a href="https://josefaidt.dev/"&gt;Josef Aidt&lt;/a&gt; pointed out while reviewing an early draft of this article, our use case for &lt;code&gt;useReducer&lt;/code&gt; in the sandbox above has certain performance implications. Since each input's &lt;code&gt;onChange&lt;/code&gt; function fires each time an input's value changes, we are actually causing our component to re-render on each key press. This is alright for demonstration purposes, but is something to be aware of when building production apps.&lt;/p&gt;

&lt;p&gt;Two ways we could avoid this are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Adding a debounce to each input, so that we do not trigger a state update on each keypress.&lt;/li&gt;
&lt;li&gt;Storing our input values in &lt;code&gt;ref&lt;/code&gt;s instead of &lt;code&gt;useReducer&lt;/code&gt; as changing the value of a &lt;code&gt;ref&lt;/code&gt; does not cause our component to re-render (see my useRef article for more on this).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now, go forth and be performant!&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>React Hooks Revisited: useCallback</title>
      <dc:creator>ryanharris.dev</dc:creator>
      <pubDate>Wed, 16 Sep 2020 12:17:01 +0000</pubDate>
      <link>https://dev.to/ryanharris/react-hooks-revisited-usecallback-ph3</link>
      <guid>https://dev.to/ryanharris/react-hooks-revisited-usecallback-ph3</guid>
      <description>&lt;h3&gt;
  
  
  Before you proceed...
&lt;/h3&gt;

&lt;p&gt;If you haven't read my useMemo article yet, I &lt;strong&gt;highly suggest you go back and do so&lt;/strong&gt; now! In that article, we covered important concepts like &lt;a href="https://en.wikipedia.org/wiki/Memoization"&gt;memoization&lt;/a&gt;, which we will continue discussing below.&lt;/p&gt;

&lt;p&gt;Since &lt;code&gt;useMemo&lt;/code&gt; and &lt;code&gt;useCallback&lt;/code&gt; are similar (with one key difference), it will be important to understand how &lt;code&gt;useMemo&lt;/code&gt; works before proceeding.&lt;/p&gt;

&lt;h3&gt;
  
  
  What's the difference?
&lt;/h3&gt;

&lt;p&gt;Both &lt;code&gt;useMemo&lt;/code&gt; and &lt;code&gt;useCallback&lt;/code&gt; utilize memoization to optimize performance, however, there is a subtle difference between them. While &lt;code&gt;useMemo&lt;/code&gt; returns a memoized value resulting from the logic contained within the hook's body, &lt;code&gt;useCallback&lt;/code&gt; returns a memoized version of the &lt;strong&gt;function itself&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;In the code block below, I've taken the &lt;code&gt;useCallback&lt;/code&gt; example from the &lt;a href="https://reactjs.org/docs/hooks-reference.html#usecallback"&gt;React docs&lt;/a&gt; and placed it next to its &lt;code&gt;useMemo&lt;/code&gt; equivalent to better illustrate the difference:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// memoizedFunction is a function&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;memoizedFunction&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useCallback&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;doSomething&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;

&lt;span class="c1"&gt;// memoizedFunction is the value returned from doSomething(a, b)&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;memoizedValue&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useMemo&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;doSomething&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, &lt;code&gt;useMemo&lt;/code&gt; and &lt;code&gt;useCallback&lt;/code&gt; achieve the same thing: optimizing performance by returning cached values when a function has already been executed using the arguments it receives. Since they return different values, both hooks offer you a different way to leverage memoization based on your specific use-case.&lt;/p&gt;

&lt;h3&gt;
  
  
  In practice
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;useCallback&lt;/code&gt; is useful because you can assign a memoized function to a variable and pass it around your application. This allows you to avoid re-creating the caching mechanism that memoization uses to improve performance.&lt;/p&gt;

&lt;p&gt;It also makes our lives easier because we do not need to duplicate &lt;code&gt;useMemo&lt;/code&gt; logic in multiple places. We also don't need to import/export anything. Instead, we can just pass the memoized function as a prop and allow another component to consume it.&lt;/p&gt;

&lt;p&gt;In the sandbox below, I've taken the code from our useMemo example and refactored it to use &lt;code&gt;useCallback&lt;/code&gt;:&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://codesandbox.io/embed/hooksusecallback-89w2p"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;Like with &lt;code&gt;useMemo&lt;/code&gt;, our &lt;code&gt;useCallback&lt;/code&gt; hook is returning a memoized value. However, in this case, it is a memoized version of the anonymous function passed to it, &lt;strong&gt;not&lt;/strong&gt; the function's return value.&lt;/p&gt;

&lt;p&gt;For demonstration purposes, we have two map components on this page (i.e. &lt;code&gt;MapOne&lt;/code&gt; and &lt;code&gt;MapTwo&lt;/code&gt;), which render -- you guessed it -- maps. If we assume they both plot coordinates in the same way, we can now pass &lt;code&gt;createMapCoordinates&lt;/code&gt; to both components, allowing them to utilize the memoized function internally without having to recreate it in both places.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;myFunction&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;doStuff&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you think about it, what we're doing here with &lt;code&gt;useCallback&lt;/code&gt; isn't too much different from the snippet above since both of them create a variable and assign a function as its value. Our hook just memoizes the function so we can optimize our applications performance!&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>React Hooks Revisited: useMemo</title>
      <dc:creator>ryanharris.dev</dc:creator>
      <pubDate>Tue, 15 Sep 2020 13:26:48 +0000</pubDate>
      <link>https://dev.to/ryanharris/react-hooks-revisited-usememo-hc7</link>
      <guid>https://dev.to/ryanharris/react-hooks-revisited-usememo-hc7</guid>
      <description>&lt;p&gt;Up until this point in the series, I have been generally familiar with the hooks we've covered and have used them before at work. It wasn't until I recently started working in a new codebase that I came across &lt;a href="https://reactjs.org/docs/hooks-reference.html#usememo"&gt;&lt;code&gt;useMemo&lt;/code&gt;&lt;/a&gt;. Not understanding how it worked or how to debug it was a large part of why I chose to write this series in the first place.&lt;/p&gt;

&lt;h3&gt;
  
  
  What is "memoization"?
&lt;/h3&gt;

&lt;p&gt;If you look at the React docs, they say that the &lt;code&gt;useMemo&lt;/code&gt; hook "returns a memoized value". &lt;a href="https://en.wikipedia.org/wiki/Memoization"&gt;Memoization&lt;/a&gt; was &lt;strong&gt;not&lt;/strong&gt; a term I was familiar with when I first read that, so don't worry if you haven't heard of it either. We're in the same boat!&lt;/p&gt;

&lt;p&gt;Memoization is an optimization strategy that returns cached values from functions that have previously been invoked with the same arguments. In other words, instead of recalculating its return value, the function will return a cached value. This is useful when you have functions doing memory intensive operations and want to minimize how often they're invoked.&lt;/p&gt;

&lt;p&gt;Here's my mental model for how this works:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Value must be calculated&lt;/span&gt;
&lt;span class="nx"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;// Value must be calculated&lt;/span&gt;
&lt;span class="nx"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;// Cached value returned&lt;/span&gt;
&lt;span class="nx"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you want to read more about memoization, checkout &lt;a href="https://scotch.io/tutorials/understanding-memoization-in-javascript#toc-a-functional-approach"&gt;this article&lt;/a&gt; on &lt;a href="https://scotch.io"&gt;Scotch.io&lt;/a&gt; by &lt;a href="https://twitter.com/worldclassdev"&gt;Philip Obosi&lt;/a&gt;. He takes a deeper look at memoization and how to implement your own memoized functions using plain JavaScript.&lt;/p&gt;

&lt;h3&gt;
  
  
  Anatomy of useMemo
&lt;/h3&gt;

&lt;p&gt;As mentioned, the &lt;code&gt;useMemo&lt;/code&gt; hook returns a "memoized value" and takes two arguments:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;A function&lt;/li&gt;
&lt;li&gt;A dependency array&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Here's an example of how it looks directly from the React docs:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;memoizedValue&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useMemo&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;computeExpensiveValue&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you have read my articles on useEffect and useLayoutEffect, you'll probably recognize this function signature. Just like those hooks, &lt;code&gt;useMemo&lt;/code&gt; executes the logic inside the function passed to it &lt;strong&gt;only&lt;/strong&gt; when one of the values in the dependency array changes. If no array is passed, &lt;code&gt;useMemo&lt;/code&gt; will re-calculate its return value on &lt;strong&gt;every&lt;/strong&gt; render.&lt;/p&gt;

&lt;p&gt;The difference here is that &lt;code&gt;useMemo&lt;/code&gt; is not intended to cause side effects -- those should be handled in the appropriately named &lt;code&gt;useEffect&lt;/code&gt; or &lt;code&gt;useLayoutEffect&lt;/code&gt; hooks. &lt;code&gt;useMemo&lt;/code&gt; simply calculates and returns a value based on the function and dependency array passed as arguments and helps handle expensive computations that may cause performance issues.&lt;/p&gt;

&lt;h3&gt;
  
  
  Optimization
&lt;/h3&gt;

&lt;p&gt;According to the React docs, &lt;code&gt;useMemo&lt;/code&gt; is meant to be a &lt;strong&gt;performance optimization&lt;/strong&gt;. They suggest you get your code to work without &lt;code&gt;useMemo&lt;/code&gt; and implement it after the fact.&lt;/p&gt;

&lt;p&gt;One thing to note, however, is that you can't really guarantee that &lt;code&gt;useMemo&lt;/code&gt; will return a cached value when expected. Read the following sentence carefully:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;In the future, React may choose to “forget” some previously memoized values and recalculate them on next render, e.g. to free memory for offscreen components. ~ &lt;a href="https://reactjs.org/docs/hooks-reference.html#usememo"&gt;React docs&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;To keep things performant and properly manage memory, React may get rid of a cached value it's not actively using in order to save room for other operations. In some cases, that will cause &lt;code&gt;useMemo&lt;/code&gt; to recalculate its return value even though it had been previously in our cache.&lt;/p&gt;

&lt;h3&gt;
  
  
  In practice
&lt;/h3&gt;

&lt;p&gt;In the example below, I've created a demo to better illustrate how &lt;code&gt;useMemo&lt;/code&gt; works. For our purposes, I have stubbed out some functions in order to make the example work properly; however, pay attention to the comments as they will provide further context.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note: If you're unfamiliar with &lt;code&gt;useEffect&lt;/code&gt; or &lt;code&gt;useState&lt;/code&gt;, take a moment and check out the previous articles in this series before continuing. Otherwise, these should look pretty familiar to you.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://codesandbox.io/embed/hooksusememo-kfgvu"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;Here, our &lt;code&gt;&amp;lt;App /&amp;gt;&lt;/code&gt; component does three things:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Makes a call to the NASA API in a &lt;code&gt;useEffect&lt;/code&gt; hook and fetches a list of NASA facilities, which we store in &lt;code&gt;useState&lt;/code&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;fetch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;https://data.nasa.gov/resource/gvk9-iz74.json&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;res&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;json&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;json&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="nx"&gt;setNasaLocations&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;json&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;})&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;catch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;err&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Error fetching data&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;err&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;[])&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Observes the &lt;code&gt;&amp;lt;input /&amp;gt;&lt;/code&gt; in our return and stores its value in another &lt;code&gt;useState&lt;/code&gt; hook
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;inputValue&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;setInputValue&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;""&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;input&lt;/span&gt;
  &lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;search&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
  &lt;span class="nx"&gt;type&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;search&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
  &lt;span class="nx"&gt;onChange&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;setInputValue&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;currentTarget&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;)}&lt;/span&gt;
&lt;span class="sr"&gt;/&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Passes a filtered array to &lt;code&gt;&amp;lt;MapView /&amp;gt;&lt;/code&gt; via the &lt;code&gt;coordinates&lt;/code&gt; prop, which represents location information for each facility
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;MapView&lt;/span&gt; &lt;span class="nx"&gt;coordinates&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;mapCoordinates&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="sr"&gt;/&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Technically, we could achieve these three goals without using &lt;code&gt;useMemo&lt;/code&gt;, however, the NASA API returns to us a list of 484 facilities, which we iterate over in &lt;code&gt;createMapCoordinates()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This is &lt;strong&gt;expensive&lt;/strong&gt; work, especially if the function runs frequently. On top of that, it calls another function for each item in the array (i.e. &lt;code&gt;createCoordsForLocation()&lt;/code&gt;), which currently returns a plain JavaScript object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;createCoordsForLocation&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;lat&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;long&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="na"&gt;latitude&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;lat&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;longitude&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;long&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But imagine that &lt;code&gt;createCoordsForLocation()&lt;/code&gt; called a backend service for each item in the list to compute its geographic coordinates. This would make our already expensive &lt;code&gt;createMapCoordinates()&lt;/code&gt; call that much more memory intensive. Since we need to do this to make our app function properly, we can leverage &lt;code&gt;useMemo&lt;/code&gt; to optimize performance.&lt;/p&gt;

&lt;p&gt;Let's look at our use case:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;mapCoordinates&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useMemo&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;createMapCoordinates&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;inputValue&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;nasaLocations&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;inputValue&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;nasaLocations&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First, look at the dependency array (i.e. &lt;code&gt;[inputValue, nasaLocations]&lt;/code&gt;). Like &lt;code&gt;useEffect&lt;/code&gt;, this tells &lt;code&gt;useMemo&lt;/code&gt; only to run when either of those values change. Right now, we only make a call for &lt;code&gt;nasaLocations&lt;/code&gt; on initial render, so its value will only change once, which triggers the hook.&lt;/p&gt;

&lt;p&gt;Our other value (i.e. &lt;code&gt;inputValue&lt;/code&gt;), represents the value the user has entered in the &lt;code&gt;&amp;lt;input /&amp;gt;&lt;/code&gt;. Anytime the user adds or removes characters from the input, the &lt;code&gt;inputValue&lt;/code&gt; will change in our &lt;code&gt;useState&lt;/code&gt; hook and cause &lt;code&gt;useMemo&lt;/code&gt; to run again.&lt;/p&gt;

&lt;p&gt;The trick here is that since we filter our &lt;code&gt;nasaLocations&lt;/code&gt; list based on the &lt;code&gt;inputValue&lt;/code&gt;, we can use &lt;code&gt;useMemo&lt;/code&gt; to reduce computations. Since the hook will return a cached value whenever it receives inputs it has used for computation before, we will avoid re-running all the logic in &lt;code&gt;createCoordsForLocation()&lt;/code&gt; and &lt;code&gt;createMapCoordinates()&lt;/code&gt; if the &lt;code&gt;inputValue&lt;/code&gt; and &lt;code&gt;nasaLocations&lt;/code&gt; array we're passing in have already been processed.&lt;/p&gt;

&lt;p&gt;Of all the hooks we've covered thus far, &lt;code&gt;useMemo&lt;/code&gt; is one of the harder ones to illustrate as its effect on your application is not necessarily visual, but performance based. Like the React docs say, get your application logic working &lt;strong&gt;without&lt;/strong&gt; &lt;code&gt;useMemo&lt;/code&gt; to confirm the proper functionality. Then, go through your component code and identify any expensive computations as these may be great candidates for &lt;code&gt;useMemo&lt;/code&gt;!&lt;/p&gt;

&lt;p&gt;In the next article, we'll be covering &lt;code&gt;useCallback&lt;/code&gt;, which also leverages memoization, but is subtly different from &lt;code&gt;useMemo&lt;/code&gt;. Stay tuned to find out how!&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>React Hooks Revisited: useContext</title>
      <dc:creator>ryanharris.dev</dc:creator>
      <pubDate>Mon, 14 Sep 2020 17:11:41 +0000</pubDate>
      <link>https://dev.to/ryanharris/react-hooks-revisited-usecontext-d90</link>
      <guid>https://dev.to/ryanharris/react-hooks-revisited-usecontext-d90</guid>
      <description>&lt;h3&gt;
  
  
  Putting things in Context
&lt;/h3&gt;

&lt;p&gt;&lt;a href="(https://reactjs.org/docs/context.html)"&gt;Context&lt;/a&gt; is one of my favorite React APIs and has a wide variety of uses cases. I've previously written about redoing a search UI using &lt;code&gt;ref&lt;/code&gt;s and Context, as well as how to use the &lt;code&gt;useRef&lt;/code&gt; hook. This time around, we're going to cover the &lt;code&gt;useContext&lt;/code&gt; hook, which is now the way we use Context in function components.&lt;/p&gt;

&lt;p&gt;I love the Context API because it &lt;strong&gt;allows you to compartmentalize aspects of your app's data within a sub-tree of components&lt;/strong&gt;. Essentially, your child components can access data via the &lt;code&gt;value&lt;/code&gt; prop provided by the &lt;code&gt;Context.Provider&lt;/code&gt;. You can think of this like a store that's specifically scoped to this tree. The components wrapped by the Provider can choose whether or not they want to consume the data (i.e. Consumers) at all, which means you can avoid &lt;a href="https://kentcdodds.com/blog/prop-drilling" rel="noopener noreferrer"&gt;prop drilling&lt;/a&gt;. Here's a rough illustration:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/.%2F01-context-drawings.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/.%2F01-context-drawings.png" alt="With and without Context illustrations"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In &lt;a href="https://codesandbox.io/s/hooksusecontext-class-wdiii" rel="noopener noreferrer"&gt;&lt;code&gt;class&lt;/code&gt; components&lt;/a&gt;, we used a combination of &lt;code&gt;&amp;lt;Context.Provider&amp;gt;&lt;/code&gt; and &lt;code&gt;&amp;lt;Context.Consumer&amp;gt;&lt;/code&gt; tags to set up the relationship described above. However, in function components, the &lt;code&gt;&amp;lt;Context.Cosumer&amp;gt;&lt;/code&gt; syntax has been &lt;a href="https://codesandbox.io/s/hooksusecontext-hooks-8ss8k" rel="noopener noreferrer"&gt;replaced with the &lt;code&gt;useContext&lt;/code&gt; hook&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;For context (no pun intended), the snippets below show these two implementations of the same Context. Despite the syntax difference, the functionality is &lt;strong&gt;identical&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;NestedComponent&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;return &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;AppContext&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;Consumer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; 
        &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;p&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/p&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;      &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/AppContext.Consumer&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;  &lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="k"&gt;default&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;App&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;React&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;Component&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nf"&gt;render&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
      &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;div&lt;/span&gt; &lt;span class="nx"&gt;className&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;App&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;AppContext&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;Provider&lt;/span&gt; &lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Hello from App 👋&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
          &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;ChildComponent&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
            &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;GrandChild&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
              &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;NestedComponent&lt;/span&gt; &lt;span class="o"&gt;/&amp;gt;&lt;/span&gt;
            &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/GrandChild&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;          &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/ChildComponent&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;        &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/AppContext.Provider&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;      &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/div&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;    &lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Anatomy of useContext
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;useContext&lt;/code&gt; hook takes one argument, a Context object, and provides access to the values from the nearest &lt;code&gt;Context.Provider&lt;/code&gt; above it in the component tree. Any component consuming data from the &lt;code&gt;Provider&lt;/code&gt; will &lt;strong&gt;always&lt;/strong&gt; re-render any time one of the values changes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;AppContext&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;React&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;createContext&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;NestedComponent&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;appContext&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;useContext&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;AppContext&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;p&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;appContext&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/p&amp;gt;&lt;/span&gt;&lt;span class="err"&gt;;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;App&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;return &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;div&lt;/span&gt; &lt;span class="nx"&gt;className&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;App&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;AppContext&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;Provider&lt;/span&gt; &lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Hello from App 👋&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;ChildComponent&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
          &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;GrandChild&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
            &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;NestedComponent&lt;/span&gt; &lt;span class="o"&gt;/&amp;gt;&lt;/span&gt;
          &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/GrandChild&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;        &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/ChildComponent&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;      &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/AppContext.Provider&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;    &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/div&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;  &lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice that even though we're using the &lt;code&gt;useContext&lt;/code&gt; hook, the way we define our context and &lt;code&gt;Provider&lt;/code&gt; is exactly the same as our &lt;code&gt;class&lt;/code&gt; example above. The provider works the same no matter which of the following consumption syntaxes you're using:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;code&gt;useContext()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;&amp;lt;Context.Consumer&amp;gt;&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://reactjs.org/docs/context.html#classcontexttype" rel="noopener noreferrer"&gt;Class.contextType&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  In practice
&lt;/h3&gt;

&lt;p&gt;In the sandbox below, I have built out a component tree that represents a self-contained search widget using the &lt;code&gt;SearchInput&lt;/code&gt; component we built in an earlier article covering the &lt;code&gt;useRef&lt;/code&gt; hook.&lt;/p&gt;

&lt;p&gt;For the purposes of this demonstration, we are mimicking an API call by loading data about breweries in Philadelphia from &lt;code&gt;results.json&lt;/code&gt; directly into our &lt;code&gt;Search&lt;/code&gt; component and displaying them as &lt;code&gt;ResultCard&lt;/code&gt;s in the &lt;code&gt;SearchResults&lt;/code&gt; component. Then, whenever the text value in &lt;code&gt;SearchInput&lt;/code&gt; changes, we filter our results to breweries who have names containing a string matching the input text.&lt;/p&gt;

&lt;p&gt;Try it out for yourself below:&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://codesandbox.io/embed/hooksusecontext-in-practice-shd17"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;In &lt;code&gt;Search&lt;/code&gt;, we have created a &lt;code&gt;SearchContext&lt;/code&gt; by using &lt;code&gt;React.createContext()&lt;/code&gt;. By doing this, we will be able to pass down context values to &lt;code&gt;SearchResults&lt;/code&gt; and &lt;code&gt;SearchInput&lt;/code&gt; without having to prop drill through our &lt;code&gt;SearchWidget&lt;/code&gt; component. While we would only be passing props through one additonal component in this example, think about how effective this strategy would be for components nested even further!&lt;/p&gt;

&lt;p&gt;To &lt;strong&gt;provide&lt;/strong&gt; values to the children of &lt;code&gt;Search&lt;/code&gt;, we are using the &lt;code&gt;SearchContext.Provider&lt;/code&gt; to pass data via the &lt;code&gt;value&lt;/code&gt; prop. We've constructed and are passing an object that has two values:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;results&lt;/code&gt; - An array of objects representing breweries&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;setInputValue&lt;/code&gt; - The setter function from the &lt;code&gt;useState&lt;/code&gt; hook in &lt;code&gt;Search&lt;/code&gt; that we're using to store the text value from &lt;code&gt;SearchInput&lt;/code&gt; (i.e. &lt;code&gt;inputValue&lt;/code&gt;)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;With the &lt;code&gt;Provider&lt;/code&gt; set up, any of &lt;code&gt;Search&lt;/code&gt;'s descendant components can &lt;strong&gt;consume&lt;/strong&gt; our context values using &lt;code&gt;useContext&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;context&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;useContext&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;SearchContext&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In &lt;code&gt;SearchInput&lt;/code&gt;, we use the &lt;code&gt;setInputValue&lt;/code&gt; function passed down via our context to set the state of &lt;code&gt;inputValue&lt;/code&gt; in &lt;code&gt;Search&lt;/code&gt; whenever the user enters text in the &lt;code&gt;&amp;lt;input /&amp;gt;&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;handleInputChange&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;context&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;setInputValue&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;currentTarget&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;input&lt;/span&gt;
  &lt;span class="nx"&gt;onChange&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;handleInputChange&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
  &lt;span class="nx"&gt;ref&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;inputRef&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
  &lt;span class="nx"&gt;type&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;search&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
  &lt;span class="nx"&gt;className&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;SearchInput__input&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
&lt;span class="o"&gt;/&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By elevating this state to the &lt;code&gt;Search&lt;/code&gt; component, we are able to use its value to filter our &lt;code&gt;apiResults&lt;/code&gt; and pass down a new array (i.e. &lt;code&gt;results&lt;/code&gt;) to the &lt;code&gt;SearchResults&lt;/code&gt; component, which renders each item as a &lt;code&gt;ResultCard&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Essentially, &lt;code&gt;Context&lt;/code&gt; allows us to more easily centralize related logic and create a good data management system for this self-contained subtree of components. Theoretically, we could repurpose this widget pretty easily by using different API data and updating a few prop names. Pretty cool!&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>React Hooks Revisited: useRef</title>
      <dc:creator>ryanharris.dev</dc:creator>
      <pubDate>Thu, 10 Sep 2020 11:56:07 +0000</pubDate>
      <link>https://dev.to/ryanharris/react-hooks-revisited-useref-17gb</link>
      <guid>https://dev.to/ryanharris/react-hooks-revisited-useref-17gb</guid>
      <description>&lt;h3&gt;
  
  
  What are refs?
&lt;/h3&gt;

&lt;p&gt;If you read my last article, about the differences between &lt;code&gt;useEffect&lt;/code&gt; and &lt;code&gt;useLayoutEffect&lt;/code&gt;, you may remember seeing some code snippets that looked like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;greenSquare&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;querySelector&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;.App__square&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="nx"&gt;greenSquare&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;style&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;transform&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;translate(-50%, -50%)&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
  &lt;span class="nx"&gt;greenSquare&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;style&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;left&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;50%&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
  &lt;span class="nx"&gt;greenSquare&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;style&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;top&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;50%&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;

&lt;span class="nx"&gt;useLayoutEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;greenSquare&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;querySelector&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;.App__square&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="nx"&gt;greenSquare&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;style&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;transform&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;translate(-50%, -50%)&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
  &lt;span class="nx"&gt;greenSquare&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;style&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;left&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;50%&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
  &lt;span class="nx"&gt;greenSquare&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;style&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;top&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;50%&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In these examples, we're directly accessing the DOM in order to select and manipulate an element (i.e. &lt;code&gt;.App__square&lt;/code&gt;), which is considered an &lt;a href="https://en.wikipedia.org/wiki/Anti-pattern"&gt;anti-pattern&lt;/a&gt; in React because it manages UI state via a &lt;a href="https://reactjs.org/docs/faq-internals.html#what-is-the-virtual-dom"&gt;virtual DOM&lt;/a&gt; and comparing it to the browser's version. Then, the framework handles the work of &lt;a href="https://reactjs.org/docs/reconciliation.html"&gt;reconciling&lt;/a&gt; the two. However, there &lt;strong&gt;are&lt;/strong&gt; cases where we need may need to break this rule. That's where &lt;code&gt;refs&lt;/code&gt; come in.&lt;/p&gt;

&lt;p&gt;While the React docs cite a few examples where using &lt;code&gt;refs&lt;/code&gt; would be appropriate, including managing focus, triggering animations, and working with third party libraries, they also warn against overusing them.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Avoid using refs for anything that can be done declaratively. ~ &lt;a href="https://reactjs.org/docs/refs-and-the-dom.html#when-to-use-refs"&gt;React docs&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;For a practical example of how to use &lt;code&gt;refs&lt;/code&gt; in your React app, &lt;a href="https://ryanharris.dev/2019-10-27-redoing-search/"&gt;checkout my previous article about rebuilding a search UI&lt;/a&gt; using &lt;code&gt;refs&lt;/code&gt; and React Context. We'll also cover the ins and outs of Context in the next article in this series.&lt;/p&gt;

&lt;p&gt;In the next section, we'll look more closely at the &lt;code&gt;useRef&lt;/code&gt; hook and its syntax.&lt;/p&gt;

&lt;h3&gt;
  
  
  Anatomy of useRef
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;...useRef is like a “box” that can hold a mutable value... ~ &lt;a href="https://reactjs.org/docs/hooks-reference.html#useref"&gt;React docs&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The &lt;code&gt;useRef&lt;/code&gt; hook only takes one argument: its initial value. This can be any valid JavaScript value or JSX element. Here are a few examples:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// String value&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;stringRef&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useRef&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;initial value&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;// Array value&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;arrayRef&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useRef&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;

&lt;span class="c1"&gt;// Object value&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;objectRef&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useRef&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
  &lt;span class="na"&gt;firstName&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Ryan&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;lastName&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Harris&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Essentially, you can store any value in your &lt;code&gt;ref&lt;/code&gt; and then access it via the &lt;code&gt;ref&lt;/code&gt;'s &lt;code&gt;current&lt;/code&gt; field. For example, if we logged out the variables from the snippet above, we would see:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;stringRef&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;// {&lt;/span&gt;
&lt;span class="c1"&gt;//   current: "initial value"&lt;/span&gt;
&lt;span class="c1"&gt;// }&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;arrayRef&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;// {&lt;/span&gt;
&lt;span class="c1"&gt;//   current: [1, 2, 3]&lt;/span&gt;
&lt;span class="c1"&gt;// }&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;objectRef&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;// {&lt;/span&gt;
&lt;span class="c1"&gt;//   current: {&lt;/span&gt;
&lt;span class="c1"&gt;//     firstName: 'Ryan',&lt;/span&gt;
&lt;span class="c1"&gt;//     lastName: 'Harris'&lt;/span&gt;
&lt;span class="c1"&gt;//   }&lt;/span&gt;
&lt;span class="c1"&gt;// }&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As I mentioned in the intro, &lt;code&gt;refs&lt;/code&gt; are primarily used for accessing the DOM. Below is an example of how you would define and use a &lt;code&gt;ref&lt;/code&gt; in the context of a &lt;code&gt;class&lt;/code&gt; component:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nx"&gt;MyComponent&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="nx"&gt;React&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;Component&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;constructor&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;super&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;inputRef&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;React&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;createRef&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;

  &lt;span class="nx"&gt;render&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
      &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;div&lt;/span&gt; &lt;span class="nx"&gt;className&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;App&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;input&lt;/span&gt; &lt;span class="nx"&gt;ref&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;inputRef&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="nx"&gt;type&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;text&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt; &lt;span class="o"&gt;/&amp;gt;&lt;/span&gt;
      &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/div&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;    &lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To do the same exact thing using hooks, we would leverage &lt;code&gt;useRef&lt;/code&gt; like you see in the snippet below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;MyComponent&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;inputRef&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useRef&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;div&lt;/span&gt; &lt;span class="nx"&gt;className&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;App&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;input&lt;/span&gt; &lt;span class="nx"&gt;ref&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;inputRef&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="nx"&gt;type&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;text&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt; &lt;span class="o"&gt;/&amp;gt;&lt;/span&gt;
    &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/div&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;  &lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Hopefully, those examples clearly illustrated how to define a ref. Just remember: &lt;code&gt;refs&lt;/code&gt; are a "reference" to a DOM element -- it's right in the name!&lt;/p&gt;

&lt;p&gt;&lt;code&gt;refs&lt;/code&gt; also have another less-known use case. Since a &lt;code&gt;ref&lt;/code&gt;'s value can be any JavaScript value, you can also use &lt;code&gt;refs&lt;/code&gt; as basic data stores. Usually, you would use &lt;code&gt;useState&lt;/code&gt; for something like that, however, there are time where you want to avoid uneccessary re-renders but cache a value. Updating values in state cause a re-render each time, whereas updating &lt;code&gt;refs&lt;/code&gt; &lt;strong&gt;do not cause the component to update&lt;/strong&gt;. This is a subtle, but important distinction.&lt;/p&gt;

&lt;h3&gt;
  
  
  In practice
&lt;/h3&gt;

&lt;p&gt;In the sections below, we'll walk through two examples that better illustrate how to use &lt;code&gt;useRef&lt;/code&gt; both to access DOM elements and store values without causing our component to re-render.&lt;/p&gt;

&lt;h4&gt;
  
  
  Accessing DOM elements
&lt;/h4&gt;

&lt;p&gt;For this example, I have built a small &lt;code&gt;SearchInput&lt;/code&gt; component that uses the &lt;code&gt;useRef&lt;/code&gt; hook in order to refer to the &lt;code&gt;&amp;lt;input /&amp;gt;&lt;/code&gt; element rendered by our component:&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://codesandbox.io/embed/serene-sunset-z80cl"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;In this specific case, our &lt;code&gt;SearchInput&lt;/code&gt; component takes an &lt;code&gt;autoFocus&lt;/code&gt; prop, which determines whether or not we want the &lt;code&gt;&amp;lt;input /&amp;gt;&lt;/code&gt; to be focused automatically on mount. In order to do this, we need to use a web API (i.e. &lt;code&gt;.focus()&lt;/code&gt;) and thus need to be able to directly refer to the HTML element on the page.&lt;/p&gt;

&lt;p&gt;To get this to work, the first thing we need to do is create a &lt;code&gt;ref&lt;/code&gt; and assign it to our element:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// This instantiates our ref&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;inputRef&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useRef&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="c1"&gt;// Inside our return, we point `inputRef` at our &amp;lt;input /&amp;gt; element&lt;/span&gt;
&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;input&lt;/span&gt; &lt;span class="nx"&gt;ref&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;inputRef&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="nx"&gt;type&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;search&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt; &lt;span class="nx"&gt;className&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;SearchInput__input&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt; &lt;span class="o"&gt;/&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, our &lt;code&gt;inputRef&lt;/code&gt; is pointing at the search input, so if we were to log out &lt;code&gt;inputRef.current&lt;/code&gt;, we would see our &lt;code&gt;&amp;lt;input /&amp;gt;&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;inputRef&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;current&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;// &amp;lt;input type="search" class="SearchInput__input"&amp;gt;&amp;lt;/input&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With this wired up, we can now autofocus the input on mount, as well as add some styling to make our &lt;code&gt;SearchInput&lt;/code&gt; component look more cohesive even though it is made up of multiple elements "under the hood". In order to handle the autofocus behavior, we need to use the &lt;code&gt;useLayoutEffect&lt;/code&gt; hook to focus the input prior to the DOM painting. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note: For more info on when to use &lt;code&gt;useLayoutEffect&lt;/code&gt; vs. &lt;code&gt;useEffect&lt;/code&gt;, check out my previous article in this series.&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;useLayoutEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;autoFocus&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;inputRef&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;current&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;focus&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="nx"&gt;setFocused&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;autoFocus&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By calling &lt;code&gt;inputRef.current.focus()&lt;/code&gt;, we are setting the &lt;code&gt;&amp;lt;input /&amp;gt;&lt;/code&gt; inside our component as the active element in the document. In addition, we're also updating our &lt;code&gt;focused&lt;/code&gt; value stored in a &lt;code&gt;useState&lt;/code&gt; hook in order to style our component.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;focusCn&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;focused&lt;/span&gt; &lt;span class="p"&gt;?&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;SearchInput focused&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;SearchInput&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, I have also added an event listener using a &lt;code&gt;useEffect&lt;/code&gt; hook in order to update our focus state based on mouse clicks both inside and outside of our component. Essentially, when the user clicks inside &lt;code&gt;SearchInput&lt;/code&gt;, we call &lt;code&gt;.focus()&lt;/code&gt; and update our &lt;code&gt;focused&lt;/code&gt; state to &lt;code&gt;true&lt;/code&gt;. Alternatively, when the user clicks outside the component, we call &lt;code&gt;.blur()&lt;/code&gt; and set &lt;code&gt;focused&lt;/code&gt; to &lt;code&gt;false&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;handleClick&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;target&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="nx"&gt;inputRef&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;current&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="nx"&gt;inputRef&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;current&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;focus&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
      &lt;span class="nx"&gt;setFocused&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="nx"&gt;inputRef&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;current&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;blur&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
      &lt;span class="nx"&gt;setFocused&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;

  &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;addEventListener&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;click&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;handleClick&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;removeEventListener&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;click&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;handleClick&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="p"&gt;};&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;While accessing DOM elements is a React anti-pattern (as discussed above), this example is a valid use case for &lt;code&gt;refs&lt;/code&gt; because our goal requires the use of &lt;code&gt;.focus()&lt;/code&gt;, which is only available to HTML elements.&lt;/p&gt;

&lt;h4&gt;
  
  
  Storing values without re-rendering
&lt;/h4&gt;

&lt;p&gt;In this example, I want to illustrate the subtle difference between using &lt;code&gt;useState&lt;/code&gt; and &lt;code&gt;useRef&lt;/code&gt; to store values.&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://codesandbox.io/embed/fancy-hooks-cxw57"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;Here, we have two sections that have buttons, which allow us to increment/decrement our &lt;code&gt;refValue&lt;/code&gt; or &lt;code&gt;stateValue&lt;/code&gt;, respectively. When the page initally loads, each section is assigned a random hex value as its &lt;code&gt;background-color&lt;/code&gt;. From then on, you will see the colors change whenever our &lt;code&gt;App&lt;/code&gt; component re-renders.&lt;/p&gt;

&lt;p&gt;Since updating state values cause a re-render, you should see the &lt;code&gt;stateValue&lt;/code&gt; number update every time you click on of the buttons; however, if you click on the buttons for our &lt;code&gt;refValue&lt;/code&gt;, nothing happens. This is because &lt;strong&gt;updating &lt;code&gt;ref&lt;/code&gt; values does not cause a component to re-render&lt;/strong&gt;. To demonstrate that the &lt;code&gt;refValue&lt;/code&gt; is in fact changing, I have added &lt;code&gt;console.log&lt;/code&gt; statements to the &lt;code&gt;onClick&lt;/code&gt; handlers for both buttons.&lt;/p&gt;

&lt;p&gt;While incrementing or decrementing the &lt;code&gt;refValue&lt;/code&gt; will not cause our UI to update with the proper numeric value, when you change the &lt;code&gt;stateValue&lt;/code&gt; our &lt;code&gt;refValue&lt;/code&gt; will update and its section will have a new background color. This is because our &lt;code&gt;ref&lt;/code&gt; section is re-rendered when the state value is updated since the parent component &lt;code&gt;App&lt;/code&gt; has to go through reconciliation to bring the virtual DOM and browser DOM into sync with one another. This can be a great strategy for avoiding uneccessary renders in your application and improving its performance!&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>React Hooks Revisited: useLayoutEffect</title>
      <dc:creator>ryanharris.dev</dc:creator>
      <pubDate>Wed, 09 Sep 2020 17:20:08 +0000</pubDate>
      <link>https://dev.to/ryanharris/react-hooks-revisited-uselayouteffect-pi7</link>
      <guid>https://dev.to/ryanharris/react-hooks-revisited-uselayouteffect-pi7</guid>
      <description>&lt;p&gt;Last time, we learned about the useEffect hook, how it works and when to use it. If you have not read that article yet, I &lt;strong&gt;strongly suggest you go back and do so before proceeding any further&lt;/strong&gt;. Much of what we will discuss below will be about the similarities and differences between &lt;code&gt;useEffect&lt;/code&gt; and &lt;code&gt;useLayoutEffect&lt;/code&gt;, which may not make much sense without having a good grip on the former.&lt;/p&gt;

&lt;h3&gt;
  
  
  useLayoutEffect and useEffect
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;The signature is identical to useEffect, but it fires synchronously after all DOM mutations. ~ &lt;a href="https://reactjs.org/docs/hooks-reference.html#uselayouteffect"&gt;React docs&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;While the underlying implementation and execution of these hooks does differ, you may notice that the code snippets below look quite similar. That's because these two hooks have the same function signature!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;getData&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// Define effect logic here&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;

  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;apiData&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;getData&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
  &lt;span class="nx"&gt;setData&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;apiData&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;[])&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;useLayoutEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;handleResize&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// Define effect logic here&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;

  &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;addEventListener&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;resize&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;handleResize&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;removeEventListener&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;resize&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;handleResize&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;[])&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To quickly recap, the anatomy of these hooks are comprised of three key pieces:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The effect&lt;/li&gt;
&lt;li&gt;A dependency array&lt;/li&gt;
&lt;li&gt;A cleanup function&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Since we're already pretty familiar with how these hooks are composed, let's look a bit more about what makes them different.&lt;/p&gt;

&lt;h3&gt;
  
  
  Difference between useLayoutEffect and useEffect
&lt;/h3&gt;

&lt;p&gt;As we saw above, these two hooks are quite similar in terms of their syntax and function signatures, however, the difference between them is quite subtle and has everything to do with timing.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;useEffect&lt;/code&gt; hook fires &lt;strong&gt;after render&lt;/strong&gt; so as not to block the DOM from painting and effecting your application's performance. Due to this behavior, the React documentation advises that when writing new effects you start with &lt;code&gt;useEffect&lt;/code&gt; and only reach for &lt;code&gt;useLayoutEffect&lt;/code&gt; when absolutely necessary.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;...we recommend starting with useEffect first and only trying useLayoutEffect if that causes a problem... ~ &lt;a href="https://reactjs.org/docs/hooks-reference.html#uselayouteffect"&gt;React docs&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Unlike &lt;code&gt;useEffect&lt;/code&gt;, &lt;code&gt;useLayoutEffect&lt;/code&gt; fires after all DOM mutations but &lt;strong&gt;before the DOM paints&lt;/strong&gt;. While this is the &lt;strong&gt;only&lt;/strong&gt; difference between these two hooks, it is an important distinction because of when their effects are performed.&lt;/p&gt;

&lt;p&gt;But when would you want to use one versus the other? The general rule of hand is as follows:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Use &lt;code&gt;useLayoutEffect&lt;/code&gt; when reading, manipulating or observing the DOM&lt;/li&gt;
&lt;li&gt;Use &lt;code&gt;useEffect&lt;/code&gt; for all other effects that don't require interaction with the DOM&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If you're still a bit confused, don't worry! It can be hard to wrap your head around not only the difference between these two hooks but their specific use cases, as well. Below, we'll look at a practical example, which will help illustrate the difference a bit more clearly.&lt;/p&gt;

&lt;h3&gt;
  
  
  In practice
&lt;/h3&gt;

&lt;p&gt;In both of the examples below, we have a simple application that renders a few HTML elements, namely two &lt;code&gt;div&lt;/code&gt;s and a &lt;code&gt;main&lt;/code&gt;, which we can see in &lt;code&gt;App.js&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
  &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;div&lt;/span&gt; &lt;span class="nx"&gt;className&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;App&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;main&lt;/span&gt; &lt;span class="nx"&gt;className&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;App__main&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;div&lt;/span&gt; &lt;span class="nx"&gt;className&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;App__square&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt; &lt;span class="o"&gt;/&amp;gt;&lt;/span&gt;
    &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/main&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;  &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/div&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Above each &lt;code&gt;&amp;lt;App /&amp;gt;&lt;/code&gt;'s return, you will see an effect defined with either &lt;code&gt;useEffect&lt;/code&gt; or &lt;code&gt;useLayoutEffect&lt;/code&gt;. The snippet below shows them side-by-side:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;useLayoutEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;greenSquare&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;querySelector&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;.App__square&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="nx"&gt;greenSquare&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;style&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;transform&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;translate(-50%, -50%)&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
  &lt;span class="nx"&gt;greenSquare&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;style&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;left&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;50%&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
  &lt;span class="nx"&gt;greenSquare&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;style&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;top&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;50%&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;

&lt;span class="nx"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;greenSquare&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;querySelector&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;.App__square&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="nx"&gt;greenSquare&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;style&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;transform&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;translate(-50%, -50%)&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
  &lt;span class="nx"&gt;greenSquare&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;style&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;left&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;50%&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
  &lt;span class="nx"&gt;greenSquare&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;style&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;top&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;50%&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As I am sure you've noticed by now, the effect function passed to both hooks are &lt;strong&gt;exactly the same&lt;/strong&gt;. Again, the big difference here is the timing of when these effects run.&lt;/p&gt;

&lt;p&gt;To start, let's look at the sandbox using &lt;code&gt;useEffect&lt;/code&gt;. You should see the purple circle appear in the top left-hand corner of the screen before it is quickly repositioned and moved to the center of the screen. This happens because &lt;strong&gt;useEffect runs after render&lt;/strong&gt;, so the effect isn't executed till after the DOM paints, which is what causes the unwanted flash of content.&lt;/p&gt;

&lt;p&gt;Now, let's look at the &lt;code&gt;useLayoutEffect&lt;/code&gt; hook. If you refresh the page, you should always see the purple circle in the center of the screen and no longer see the circle get quickly repositioned. This is because &lt;strong&gt;useLayoutEffect runs before the DOM paints&lt;/strong&gt;, so the circle has already been positioned correctly before we see the first visual representation of our page. In this example, it would be more appropriate to use &lt;code&gt;useLayoutEffect&lt;/code&gt; because we would not want our users to see what looks like a visual bug.&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://codesandbox.io/embed/hooksuselayouteffect-uselayouteffect-jxvzg"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;h3&gt;
  
  
  Next steps
&lt;/h3&gt;

&lt;p&gt;In the examples above, we are using vanilla JavaScript to access and modify the document, which is considered an anti-pattern in React. A more appropriate way to do this would be to use a &lt;code&gt;ref&lt;/code&gt; instead of accessing the DOM directly. Luckily, we'll be covering that in the next article about &lt;code&gt;useRef&lt;/code&gt;!&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>React Hooks Revisited: useEffect</title>
      <dc:creator>ryanharris.dev</dc:creator>
      <pubDate>Tue, 08 Sep 2020 18:18:59 +0000</pubDate>
      <link>https://dev.to/ryanharris/react-hooks-revisited-useeffect-4ph</link>
      <guid>https://dev.to/ryanharris/react-hooks-revisited-useeffect-4ph</guid>
      <description>&lt;p&gt;In my last article, we learned about one of the most commonly used hooks, &lt;code&gt;useState&lt;/code&gt;. This time around, we are going to look at another commonly used hook: &lt;code&gt;useEffect&lt;/code&gt;:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed (we'll refer to it as our "effect"), and call it later after performing DOM updates. ~ &lt;a href="https://reactjs.org/docs/hooks-effect.html"&gt;React docs&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  What are effects?
&lt;/h3&gt;

&lt;p&gt;Effects, a shorthand for "side effects", represent component operations or actions that cannot be done during the render phase. Examples of this can include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Fetching data from an API&lt;/li&gt;
&lt;li&gt;Setting up data subscriptions or document event listeners&lt;/li&gt;
&lt;li&gt;Manipulating the DOM&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We can also further classify them into two categories:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Effects that require cleanup&lt;/li&gt;
&lt;li&gt;Effects that don't&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;For example, if we attach an event listener to the document, we will want to remove it when the component unmounts as this will help with performance and avoid conflicting listeners. On the other hand, something like updating the &lt;code&gt;document.title&lt;/code&gt; does not require any further work when the component unmounts.&lt;/p&gt;

&lt;p&gt;To make cleaning up effects easy, the &lt;code&gt;useEffect&lt;/code&gt; API allows you to optionally return a function from the hook, which does the work of removing listeners, subscriptions, etc. Previously, you would've needed to leverage both the &lt;code&gt;componentDidMount&lt;/code&gt; and &lt;code&gt;componentDidUnmount&lt;/code&gt; lifecycle methods to achieve this whereas &lt;code&gt;useEffect&lt;/code&gt; allows us to take care of it all at once.&lt;/p&gt;

&lt;h3&gt;
  
  
  Anatomy of useEffect
&lt;/h3&gt;

&lt;p&gt;Now that we've talked about what &lt;code&gt;useEffect&lt;/code&gt; does, let's take a look at the syntax:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="c1"&gt;// 2. This function body is your effect&lt;/span&gt;
  &lt;span class="nb"&gt;window&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;addEventListener&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;resize&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;handleResize&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// 1. Optionally clean up effects inside this function&lt;/span&gt;
    &lt;span class="nb"&gt;window&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;removeEventListener&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;resize&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;handleResize&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;[])&lt;/span&gt; &lt;span class="c1"&gt;// 3. Conditionally execute based on dependencies array&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If this syntax looks a bit strange, don't worry. We'll break down each piece before moving on to some practical examples. Let's start with the optional cleanup function since we were just talking about it.&lt;/p&gt;

&lt;h4&gt;
  
  
  1. Cleanup
&lt;/h4&gt;

&lt;p&gt;Inside our effect, we can optionally return a function. This function will perform any cleanup work we want to happen when this component unmounts. In our example, we are removing the event listener from the window to make sure it doesn't keep listening/firing after the component is no longer in the DOM.&lt;/p&gt;

&lt;h4&gt;
  
  
  2. The effect
&lt;/h4&gt;

&lt;p&gt;The first argument &lt;code&gt;useEffect&lt;/code&gt; takes is a function. This function &lt;strong&gt;is your effect&lt;/strong&gt; and defines the work you want to do whenever the component mounts. In this case, we are simply adding an event listener to the window that executes the &lt;code&gt;handleResize&lt;/code&gt; function on &lt;code&gt;resize&lt;/code&gt;.&lt;/p&gt;

&lt;h4&gt;
  
  
  3. Dependency array
&lt;/h4&gt;

&lt;p&gt;The optional second argument in this example is what's known as the "dependency array". Essentially, leveraging this array allows you to control the conditional execution of the effect based upon changing prop or state values in the component. We will talk about this more in-depth in the next section.&lt;/p&gt;

&lt;h3&gt;
  
  
  What is the dependency array?
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;By default, effects run after every completed render, but you can choose to fire them only when certain values have changed. ~ &lt;a href="https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects"&gt;React docs&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;As I mentioned above, the dependency array is an optional secondary argument passed to the &lt;code&gt;useEffect&lt;/code&gt; hook. Its purpose is to allow you to more easily control the execution of your effects based upon the values within you component. In class components, we would most likely need to use the &lt;code&gt;componentDidUpdate&lt;/code&gt; lifecycle method to achieve the same results, which would've looked something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;componentDidUpdate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;prevProps&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;prevState&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;prevState&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;cardTypes&lt;/span&gt; &lt;span class="o"&gt;!==&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;state&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;cardTypes&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// Your effect logic would live here&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using the dependencies array we can do things like:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Fire the effect everytime the component renders
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;cardTypes&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;fetchCardTypes&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
  &lt;span class="nx"&gt;setCardTypes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;cardTypes&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Fire the effect only upon the first render
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;cardTypes&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;fetchCardTypes&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
  &lt;span class="nx"&gt;setCardTypes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;cardTypes&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;[])&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Fire the effect only when certain prop or state values have changed
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;cardTypes&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;fetchCardTypes&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
  &lt;span class="nx"&gt;setCardTypes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;cardTypes&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;cards&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One thing to note here is that while you can also use &lt;code&gt;if&lt;/code&gt; statements within your &lt;code&gt;useEffect&lt;/code&gt; hooks to conditionally execute logic, &lt;strong&gt;you cannot wrap hooks in &lt;code&gt;if&lt;/code&gt; statements&lt;/strong&gt;. Part of how React keeps effects predictable is to run them all upon render. Skipping effects like this is considered bad practice, so don't do it!&lt;/p&gt;

&lt;h3&gt;
  
  
  In practice
&lt;/h3&gt;

&lt;p&gt;In the sandbox below, I've create a small application that leverages &lt;code&gt;useEffect&lt;/code&gt; in numerous ways in order to serve us information about the latest weather on Mars. Elon Musk, eat your heart out!&lt;/p&gt;

&lt;p&gt;For simplicity's sake, I've created two components: &lt;code&gt;App&lt;/code&gt; and &lt;code&gt;WeatherDisplay&lt;/code&gt;. The former handles fetching our data from the Nasa API and our application logic, whearas the latter simply displays the data we've passed down to it as props. Because of that, all of our &lt;code&gt;useEffect&lt;/code&gt; hooks live inside of &lt;code&gt;App&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;As you will notice, we actually have &lt;strong&gt;three&lt;/strong&gt; &lt;code&gt;useEffect&lt;/code&gt; hooks inside of our component, which may seem a bit strange, but is the whole idea of hooks! This allows us to compartmentalize our component logic and more easily reason about the effects they trigger. In this example, our three hooks are doing the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Hook #1 sets the title of our document &lt;strong&gt;on every render&lt;/strong&gt; using the value of our &lt;code&gt;day&lt;/code&gt; state&lt;/li&gt;
&lt;li&gt;Hook #2 fetchs our API data &lt;strong&gt;only on the first render&lt;/strong&gt; as we don't want to make be making continually API calls as the component updates&lt;/li&gt;
&lt;li&gt;Hook #3 parses the proper data object based on the value of &lt;code&gt;day&lt;/code&gt; &lt;strong&gt;any time the value of &lt;code&gt;day&lt;/code&gt; or &lt;code&gt;data&lt;/code&gt;&lt;/strong&gt; change&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Each of these hooks is using a diffrent variation of the optional dependency array we discussed earlier. Look at the code a bit more closely -- do you know why each array looks the way it does?&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://codesandbox.io/embed/hooksuseeffect-gkejk"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;Don't worry if you're still a bit confused because learning to "think in hooks" can take some time. The best way to get more comfortable with them is to use them, so feel free to fork the sandbox above and play around with the code. As a good place to start, try removing the dependency array from Hook #2 completely. What happens?&lt;/p&gt;

&lt;p&gt;With an empty dependency array, the effect makes a request for our API data on mount and this &lt;strong&gt;only happens once&lt;/strong&gt;. Previously, we would &lt;code&gt;componentDidUpdate&lt;/code&gt; and compare the components &lt;code&gt;prevProps&lt;/code&gt; to it's current &lt;code&gt;props&lt;/code&gt; and use that to determine if there was work to be done. Now, with &lt;code&gt;useEffect&lt;/code&gt;, we no longer have to do this and can just define what prop values we care about and run the effect only when one of them changes. We'll talk more about this more later in the series.&lt;/p&gt;

&lt;p&gt;If we remove the dependency array altogether, the effect runs on &lt;strong&gt;every&lt;/strong&gt; render, which means we're making API calls every time the component re-renders. Since something simple like changing state (ex. clicking on the &lt;code&gt;Today&lt;/code&gt; or &lt;code&gt;Yesterday&lt;/code&gt; buttons) causes a re-render, we'd essentially fetch data everytime the user clicked one of the buttons. This is not good for application performance, nor your API bill.&lt;/p&gt;

&lt;p&gt;Ultimately, hooks are meant to compartmentalize application logic to make them easier to re-use and reason about. &lt;code&gt;useEffect&lt;/code&gt; is no different. Like all hooks, it runs on every render by default, but unlike other hooks, provides a way to conditionally control our logic execution (i.e. the dependency array). While &lt;code&gt;useEffect&lt;/code&gt; is often described as &lt;code&gt;componentDidMount&lt;/code&gt;, &lt;code&gt;componentDidUpdate&lt;/code&gt; and &lt;code&gt;componentWillUnmount&lt;/code&gt; altogether, I would try to avoid thinking about hooks in terms of their equivalent lifecycle methods. Instead, identify the effects that need to take place in your component, determine how often your would like the effect to run and cleanup your work (if needed) when the component unmounts.&lt;/p&gt;

&lt;p&gt;Try adding &lt;code&gt;useEffect&lt;/code&gt; to your next component. Maybe you'll get hooked.&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>React Hooks Revisited: useState</title>
      <dc:creator>ryanharris.dev</dc:creator>
      <pubDate>Mon, 07 Sep 2020 17:34:21 +0000</pubDate>
      <link>https://dev.to/ryanharris/react-hooks-revisited-usestate-g3j</link>
      <guid>https://dev.to/ryanharris/react-hooks-revisited-usestate-g3j</guid>
      <description>&lt;p&gt;One of the first hooks you'll probably encounter is &lt;code&gt;useState&lt;/code&gt;, which replaces the &lt;code&gt;setState()&lt;/code&gt; function used to update state in class components. The big difference here, however, is that &lt;code&gt;useState&lt;/code&gt; allows function components to have multiple state values as opposed to one monolithic object. The snippet below illustrates this idea (don't worry about the syntax as we'll be covering that below):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Class component state&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nx"&gt;Cart&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="nx"&gt;React&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;Component&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;constructor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;props&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;super&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;props&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;state&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="na"&gt;apples&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="na"&gt;oranges&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;25&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="na"&gt;peaches&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;40&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Function component using hooks&lt;/span&gt;
&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;Cart&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;props&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;apples&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;setApples&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;oranges&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;setOranges&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;25&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;peaches&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;setPeaches&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;40&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Not too crazy, right? In this example, all of our values are numbers but the value stored in &lt;code&gt;useState&lt;/code&gt; can be any JavaScript type, including:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Strings&lt;/li&gt;
&lt;li&gt;Booleans&lt;/li&gt;
&lt;li&gt;Objects&lt;/li&gt;
&lt;li&gt;Arrays&lt;/li&gt;
&lt;li&gt;Numbers&lt;/li&gt;
&lt;li&gt;&lt;code&gt;null&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Anatomy of useState
&lt;/h3&gt;

&lt;p&gt;Let's take one of the previous examples and look at it a bit more closely.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;apples&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;setApples&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First, let's look at what is happening on the right side of this expression. Here, we have the value of &lt;code&gt;10&lt;/code&gt; being passed as the only argument to our &lt;code&gt;useState&lt;/code&gt; hook. This sets its initial value to &lt;code&gt;10&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;On the left-hand side of the assignment, we are destructuring two values returned from &lt;code&gt;useState&lt;/code&gt; as an array: &lt;code&gt;apples&lt;/code&gt; and &lt;code&gt;setApples&lt;/code&gt;. The first (i.e. &lt;code&gt;apples&lt;/code&gt;), represents the current value of this state. In this case, the value would be &lt;code&gt;10&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The second value in the array (i.e. &lt;code&gt;setApples&lt;/code&gt;) is a setter function that allows you to update the value of &lt;code&gt;apples&lt;/code&gt; by calling &lt;code&gt;setApples(200)&lt;/code&gt;, which would update &lt;code&gt;apples&lt;/code&gt; to be equal to &lt;code&gt;200&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;While you can technically give these setter functions whatever name you want, the common convention is to prepend the value's name with &lt;code&gt;set&lt;/code&gt; (ex. &lt;code&gt;setApples&lt;/code&gt;).&lt;/p&gt;

&lt;h3&gt;
  
  
  In practice
&lt;/h3&gt;

&lt;p&gt;To better illustrate the mental model of having multiple states instead of one, I built a simplified version of an e-commerce cart.&lt;/p&gt;

&lt;p&gt;The first instance is a function component using three &lt;code&gt;useState&lt;/code&gt; hooks to manage the quantity values of how many &lt;code&gt;apples&lt;/code&gt;, &lt;code&gt;oranges&lt;/code&gt; and &lt;code&gt;peaches&lt;/code&gt; are in the user's cart. The second is a class component that is still using &lt;code&gt;setState()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;As you can see, both components do the same things: keep track of how many of each item a user wants and increment/decrement that value based on button presses.&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://codesandbox.io/embed/hooksusestate-o64ve"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;Take a look at the code and see which one you prefer. While hooks may still be new to you, can you see any benefits from using them?&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>React Hooks Revisited: Introduction</title>
      <dc:creator>ryanharris.dev</dc:creator>
      <pubDate>Mon, 07 Sep 2020 17:33:06 +0000</pubDate>
      <link>https://dev.to/ryanharris/react-hooks-revisited-introduction-450p</link>
      <guid>https://dev.to/ryanharris/react-hooks-revisited-introduction-450p</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;Hooks are functions that let you “hook into” React state and lifecycle features from function components ~ &lt;a href="https://reactjs.org/docs/hooks-overview.html#but-what-is-a-hook"&gt;React docs&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Introduced in &lt;a href="https://github.com/facebook/react/blob/master/CHANGELOG.md#1680-february-6-2019"&gt;React v16.8&lt;/a&gt;, the hooks API represents a change in how developers compose their components. Intended to compartmentalize blocks of functionality, they make reusing code across your application easier. They also mark a shift away from using &lt;code&gt;class&lt;/code&gt; components and the use of lifecycle methods.&lt;/p&gt;

&lt;p&gt;When hooks were first introduced at &lt;a href="https://www.youtube.com/playlist?list=PLPxbbTqCLbGE5AihOSExAa4wUM-P42EIJ"&gt;React Conf 2018&lt;/a&gt;, the React team explained the motivations behind them. Essentially, they wanted to solve many problems all at once:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;It can be hard to re-use logic between components&lt;/li&gt;
&lt;li&gt;Complex component files are huge&lt;/li&gt;
&lt;li&gt;Understanding classes in JavaScript can be difficult to understand (for humans and compilers)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;For a &lt;strong&gt;much&lt;/strong&gt; more detailed explanation about the origin of hooks, make sure to check out the team's full talk featuring &lt;a href="https://overreacted.io/"&gt;Dan Abramov&lt;/a&gt;, &lt;a href="https://sophiebits.com/"&gt;Sophie Alpert&lt;/a&gt; and &lt;a href="https://reacttraining.com/"&gt;Ryan Florence&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/dpw9EHDh2bM"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;h3&gt;
  
  
  Goals for the series
&lt;/h3&gt;

&lt;p&gt;When the hooks API moved out of beta, my team started using them almost immediately. However, most of the logic for the feature I was working on at the time was contained within class components still using lifecycle methods. When creating new components, I was using function components and hooks; however, the components usually weren't complex enough to leverage more than &lt;code&gt;useState&lt;/code&gt; or &lt;code&gt;useEffect&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Currently, I work in a codebase that was all written "post-class components" and I want to revisit (hence the title of this series) how they &lt;strong&gt;all&lt;/strong&gt; work, as well as when to use them.&lt;/p&gt;

&lt;p&gt;To do that, I've written an article about each hook in the standard React library. Each piece is linked below and will cover the hook in depth, including code samples illustrating how it works.&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Redoing search UI with React Context and refs</title>
      <dc:creator>ryanharris.dev</dc:creator>
      <pubDate>Thu, 10 Oct 2019 18:15:06 +0000</pubDate>
      <link>https://dev.to/ryanharris/redoing-search-ui-with-react-context-and-refs-de9</link>
      <guid>https://dev.to/ryanharris/redoing-search-ui-with-react-context-and-refs-de9</guid>
      <description>&lt;p&gt;** &lt;em&gt;Originally &lt;a href="https://blog.logrocket.com/redoing-search-ui-with-react-context-and-refs/"&gt;published&lt;/a&gt; on &lt;a href="https://logrocket.com/"&gt;LogRocket&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Recently, the product team at my company discovered the majority of our users were not utilizing filters when using our search interface.&lt;/p&gt;

&lt;p&gt;After looking at our analytics, it became apparent users weren’t engaging with filters because they didn’t know they existed.&lt;/p&gt;

&lt;p&gt;To fix this problem, we decided to rebuild our UI in order to highlight this functionality.&lt;/p&gt;

&lt;p&gt;But building a new search interface came with its own set of problems. In our case, we had three main concerns:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;By adding filter dropdown menus with nested inputs, we would need a way to easily manage focus.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;With three filter menus, we needed a way to ensure only one menu was open at any given time.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;When the user selected a filter from one of the menus, we needed to both close the menu and trigger a new search.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We achieved all of our objectives by using &lt;a href="https://blog.logrocket.com/how-and-when-to-use-reacts-new-context-api-b584e41b2704/"&gt;React’s Context API&lt;/a&gt; in conjunction with refs to create a centralized system for managing menu states and input focus.&lt;/p&gt;

&lt;p&gt;In this article, we’ll cover the following:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Context:&lt;/strong&gt; basic usage and strategies for injecting data anywhere in your component tree&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Refs:&lt;/strong&gt; what they are and why our use case calls for them&lt;/p&gt;

&lt;h3&gt;
  
  
  Context
&lt;/h3&gt;

&lt;p&gt;The official Context API was added to React in v16.3 and is intended to avoid what is commonly known as prop drilling, or manually passing props down a component tree.&lt;/p&gt;

&lt;p&gt;While there is nothing wrong with this approach, it can be unwieldy when dealing with complex component hierarchies, especially if some components don’t care about the data and are simply passing it on.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--FbfT7nJq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://blog.logrocket.com/wp-content/uploads/2019/09/Illustration-1-Without-Context-nocdn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--FbfT7nJq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://blog.logrocket.com/wp-content/uploads/2019/09/Illustration-1-Without-Context-nocdn.png" alt="Without Context"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In order to use the Context API, you need to create a &lt;code&gt;Context.Provider&lt;/code&gt; that takes a &lt;code&gt;value&lt;/code&gt; prop representing all the data you want to inject into the child components that need it.&lt;/p&gt;

&lt;p&gt;Before the advent of &lt;a href="https://blog.logrocket.com/frustrations-with-react-hooks/"&gt;Hooks&lt;/a&gt;, you would do this by using an associated &lt;code&gt;Context.Consumer&lt;/code&gt;, but in the post-Hooks world, we can leverage the &lt;code&gt;useContext&lt;/code&gt; Hook to subscribe a component to the closest Provider above it in the component tree.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--qjqxr6vE--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://blog.logrocket.com/wp-content/uploads/2019/09/Illustration-2-With-Context-nocdn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--qjqxr6vE--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://blog.logrocket.com/wp-content/uploads/2019/09/Illustration-2-With-Context-nocdn.png" alt="With Context"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this case, Context provides a way to keep track of which menu should be open in our parent component, and then passes that value down to its children who, in turn, conditionally render the appropriate dropdown.&lt;/p&gt;

&lt;p&gt;The key here is that our Context also passes down a setter function. This is important because it allows the components consuming our context value to then update the state in our parent component, which causes the tree to re-render with the new menu now visible.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--5TXL3FAz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://blog.logrocket.com/wp-content/uploads/2019/09/Illustration-3-Menu-value-and-setter-function-nocdn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--5TXL3FAz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://blog.logrocket.com/wp-content/uploads/2019/09/Illustration-3-Menu-value-and-setter-function-nocdn.png" alt="Menu value with getter and setter"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;By using the pattern described above, we can similarly manage the focus state of the various inputs in the search bar and filter menus.&lt;/p&gt;

&lt;h3&gt;
  
  
  Refs
&lt;/h3&gt;

&lt;p&gt;While they have been part of React for a while, refs can still be somewhat confusing even for more experienced developers.&lt;/p&gt;

&lt;p&gt;Essentially, React provides a special ref attribute that can be applied to any element (JSX or HTML).&lt;/p&gt;

&lt;p&gt;Depending on what type of element you assign it to, the ref provides access to that class instance or DOM element, respectively.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Applying a ref directly to an HTML element&lt;/span&gt;
&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;input&lt;/span&gt;
  &lt;span class="nx"&gt;className&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;AuthorFilterMenu__filter-input&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
  &lt;span class="nx"&gt;ref&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;authorFilterInputRef&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
  &lt;span class="nx"&gt;placeholder&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Filter by author...&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
  &lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;filterInputValue&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
  &lt;span class="nx"&gt;type&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;search&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
  &lt;span class="nx"&gt;onInput&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;setFilterInputValue&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;currentTarget&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="p"&gt;}}&lt;/span&gt;
&lt;span class="sr"&gt;/&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;
&lt;span class="c1"&gt;// Applying a ref to a React component instance&lt;/span&gt;
&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;AuthorFilterMenu&lt;/span&gt; &lt;span class="nx"&gt;ref&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;authorFilterInputRef&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="sr"&gt;/&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Though our use case requires us to go down this road, it is important to note that refs are a React antipattern because they allow direct DOM access. React does not really intend for developers to do this, so when using refs you should proceed with caution.&lt;/p&gt;

&lt;p&gt;Alternatively, React is designed to have events update the virtual DOM (a snapshot of the document object model kept in memory,) and allow the framework to update the page as needed in a process known as reconciliation.&lt;/p&gt;

&lt;p&gt;This not only makes React more performant by reducing the work done to update the page, but it also makes for a more consistent user experience.&lt;/p&gt;

&lt;p&gt;For us, we need to directly access the three &lt;code&gt;input&lt;/code&gt;s in our component tree in order to use the browser’s &lt;code&gt;.focus()&lt;/code&gt; method. Since we need to change focus states for our inputs based on user interaction, it makes sense to keep this logic in our parent component, too.&lt;/p&gt;

&lt;p&gt;We’ll create three different refs in our parent component that will point to the following:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The input in our search bar&lt;/li&gt;
&lt;li&gt;The input in our first filter menu (ex. Author)&lt;/li&gt;
&lt;li&gt;The input in our second filter menu (ex. Year)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Using our Context, we can then pass these refs down to our child components. In the child component, we destructure the appropriate &lt;code&gt;ref&lt;/code&gt; off the component’s &lt;code&gt;props&lt;/code&gt; object and assign it directly to our HTML &lt;code&gt;input&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Provide value in App.jsx&lt;/span&gt;
&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;section&lt;/span&gt; &lt;span class="nx"&gt;className&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;App__search&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;SearchContext&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;Provider&lt;/span&gt;
    &lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{{&lt;/span&gt;
      &lt;span class="na"&gt;openMenu&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;openMenu&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="na"&gt;toggleOpenMenu&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;toggleOpenMenu&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="na"&gt;addAuthor&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;addAuthor&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="na"&gt;addYear&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;addYear&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="na"&gt;selectedAuthors&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;selectedAuthors&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="na"&gt;selectedYears&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;selectedYears&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="na"&gt;authorFilterInputRef&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;authorFilterInputRef&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="na"&gt;searchBarRef&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;searchBarRef&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="na"&gt;yearFilterInputRef&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;yearFilterInputRef&lt;/span&gt;
    &lt;span class="p"&gt;}}&lt;/span&gt;
  &lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;SearchBar&lt;/span&gt; &lt;span class="o"&gt;/&amp;gt;&lt;/span&gt;
  &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/SearchContext.Provider&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/section&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;
&lt;span class="c1"&gt;// In AuthorFilterMenu.jsx, we grab the ref from the searchContext&lt;/span&gt;
&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;AuthorFilterMenu&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;props&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;contextValue&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;React&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;useContext&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;SearchContext&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;addAuthor&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nx"&gt;openMenu&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nx"&gt;selectedAuthors&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nx"&gt;authorFilterInputRef&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;contextValue&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// And then we apply it to the &amp;lt;input&amp;gt;&lt;/span&gt;
&lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
  &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;div&lt;/span&gt; &lt;span class="nx"&gt;className&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;menuCn&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;input&lt;/span&gt;
      &lt;span class="nx"&gt;className&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;AuthorFilterMenu__filter-input&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
      &lt;span class="nx"&gt;ref&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;authorFilterInputRef&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
      &lt;span class="nx"&gt;placeholder&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Filter by author...&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
      &lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;filterInputValue&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
      &lt;span class="nx"&gt;type&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;search&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
      &lt;span class="nx"&gt;onInput&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nx"&gt;setFilterInputValue&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;currentTarget&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
      &lt;span class="p"&gt;}}&lt;/span&gt;
    &lt;span class="sr"&gt;/&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;    &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;ul&lt;/span&gt; &lt;span class="nx"&gt;className&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;AuthorFilterMenu__list&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;createMenuItems&lt;/span&gt;&lt;span class="p"&gt;()}&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/ul&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;  &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/div&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, whenever one of the child components calls our menu state setter function to toggle a menu, we can add logic to also update which input is in focus.&lt;/p&gt;

&lt;p&gt;For example, if one of our filter menus is open and then closes, we would want to refocus the search input bar to allow the user to continue their query.&lt;/p&gt;

&lt;p&gt;One thing to note here is that function components don’t play well with refs.&lt;/p&gt;

&lt;p&gt;In order to pass a &lt;code&gt;ref&lt;/code&gt; into a function component, you will need to use &lt;code&gt;React.forwardRef&lt;/code&gt;, which creates a new component that receives a &lt;code&gt;ref&lt;/code&gt; attribute and then passes it on to another component below.&lt;/p&gt;

&lt;p&gt;For a more detailed look at how to use &lt;code&gt;forwardRef&lt;/code&gt;, check out the &lt;a href="https://reactjs.org/docs/react-api.html#reactforwardref"&gt;official React docs&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;While Context is a relatively new API and refs are somewhat of an antipattern, they compliment each other well in this case. By combining the two together, we are able to create a more straightforward way of managing both display and focus states within our new search interface.&lt;/p&gt;

&lt;p&gt;While we didn’t use any stores in this example, you could easily wire one up and include it in this data flow.&lt;/p&gt;

&lt;p&gt;For example, in the project I built at work, my parent component was subscribed to a store that provided a list of the items to be rendered in our dropdown menus.&lt;/p&gt;

&lt;p&gt;Once the parent received this data, it added it to our Context’s &lt;code&gt;value&lt;/code&gt; prop and passed it down to the child components.&lt;/p&gt;

&lt;p&gt;Ultimately, the ability to centrally locate logic in this way allows for a more consistent user experience.&lt;/p&gt;

&lt;p&gt;By using Context, we easily decoupled our business logic and data fetching from the presentation and functionality of our UI components.&lt;/p&gt;

&lt;p&gt;We also made our code easier for other developers to read in the future, which is never a bad thing!&lt;/p&gt;

&lt;p&gt;For the full tutorial, check out this &lt;a href="https://codesandbox.io/s/laughing-lichterman-lxl1y"&gt;demo&lt;/a&gt;: &lt;br&gt;
&lt;iframe src="https://codesandbox.io/embed/lxl1y"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

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