<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Joe Tonelli on Medium]]></title>
        <description><![CDATA[Stories by Joe Tonelli on Medium]]></description>
        <link>https://medium.com/@joetoenails?source=rss-60d801ca284------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GjqPR23_2JrBQtpDJhqPeA.jpeg</url>
            <title>Stories by Joe Tonelli on Medium</title>
            <link>https://medium.com/@joetoenails?source=rss-60d801ca284------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 13:11:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joetoenails/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Level Up Your React Game With These Hooks]]></title>
            <link>https://joetoenails.medium.com/level-up-your-react-game-with-these-hooks-5e4b131f5535?source=rss-60d801ca284------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e4b131f5535</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Joe Tonelli]]></dc:creator>
            <pubDate>Tue, 16 Feb 2021 22:58:33 GMT</pubDate>
            <atom:updated>2021-02-16T22:58:33.258Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leveling Up Your React Game With Hooks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nc8Hy9khFs9Bi1oGp8mqUA.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/mirandableijenberg-3434377/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=2669219">Miranda Bleijenberg</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=2669219">Pixabay</a></figcaption></figure><p>If you’re working towards a career in web development or you’re already an experienced developer, you’ve likely heard of <a href="https://reactjs.org/">React</a>. If you haven’t, or you’re just learning about React for the first time, just know that at its simplest, React is a tool to make building functionality into your website easier. I highly recommend going to their <a href="https://reactjs.org/">website</a> and checking out a few tutorials. The documentation is well-written, clear, and makes learning easy, so don’t be scared!</p><p>For the purposes of this post however, I’m going to assume you have some base knowledge about React, and know a bit about creating components, passing down props, and some other basics. Again, if that’s gibberish to you, just go to the docs! Today, we’ll talk a bit about React’s Hooks, References and Context. Since I learn best myself by looking at simple, practical applications of concepts (and I think others do too!), I’ll do my best to provide examples and use-cases for each of these tools, to better help you, dear reader! You’ll see no “foo” “bar” “baz” here. Why people write documentation with meaningless words, I do not know, but I hope by the end of this blog, you’ll have a few more tools in your toolbelt to help with your next project. Off we go!</p><h3>React Hooks</h3><p>At first read, you might be unsure exactly what “hooks” are when it comes to React. I’ve been told, “Oh, they allow you to “hook” into different things inside of a React component,” however I don’t find that explanation particularly helpful. Perhaps it’s more helpful to think of hooks as specialized React functions that allow you to create or access specific necessary pieces of a component. Hooks come in many different flavors and types, so if that description still sounds a bit vague, let’s just look at some of the most common hooks, and demonstrate how they’re used.</p><h3>UseState()</h3><p>The useState() hook allows for the creation and use of state inside of a functional component, something that was previously only accessible inside of React’s class components. Let’s look at the code below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fjoetoenails%2Fembed%2Fpreview%2FRworZoR%3Fheight%3D600%26slug-hash%3DRworZoR%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fjoetoenails%2Fpen%2FRworZoR%3Feditors%3D0010&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/b94858a3da38d66498e340f52639b9d5/href">https://medium.com/media/b94858a3da38d66498e340f52639b9d5/href</a></iframe><p>First note that we’re calling the hook with “React.useState()”. For all React hooks (and in fact for all features I’ll mention here) you’ll need to use React dot (the hook name), or specifically import the hook or feature alongside your core React import.</p><p>Looking at the assignment to useState, you’ll notice we’re initializing the state with two variables placed inside of an array. The first variable (“status”) is a direct reference to the piece of state you want to maintain. Remember, if and when this value changes, it will cause the component it is located in to re-render (and potentially cause other effects). It functions exactly as a piece of state would inside of a class component. The second variable (“setStatus”) is a specific function by which you can update the associated piece of state. In this instance we use setStatus to make the “status” true or false, however you could just as easily call setStatus with any other value. Note, there is some risk here that you call setStatus with the wrong data type, so you may want to look into some<a href="https://reactjs.org/docs/static-type-checking.html"> static type checking</a> options for better security. Finally, note that setStatus is being initialized with “false”. This simply means that when the component first loads, “status” will be set to false. You can initialize a piece of state with any value.</p><h3>UseEffect()</h3><p>useEffect is the next common hook you’ll likely encounter. useEffect() is powerful, and can take on many different roles within a component’s lifespan. Most commonly, you’ll see useEffect used as a replacement for the “componentDidMount” lifecycle method. They are great places to put asynchronous calls (like requesting info from your DB), or event listeners that you want to kick off as soon as a component comes to life on the screen.</p><p>useEffect takes 2 arguments, the first being a callback function that includes all the actions you want to happen when your useEffect function fires. The second argument is an array of variables that will cause a specific useEffect to fire if, and only if, they change. All useEffects within a component (you can have many!) will fire when the component mounts, however you can limit or control if and when they fire again by passing dependencies inside that array. Remember, useEffect runs AFTER the initial component render, so make sure your component is configured to run smoothly before any changes in useEffect take place (ie: display some loading screens, or checks to see if something is undefined because it hasn’t loaded yet). Let’s go to the code!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fjoetoenails%2Fembed%2Fpreview%2FqBqbXPE%3Fheight%3D600%26slug-hash%3DqBqbXPE%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fjoetoenails%2Fpen%2FqBqbXPE%3Feditors%3D0010&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/9155d061809bc79c4d69fb3d9cfb37a5/href">https://medium.com/media/9155d061809bc79c4d69fb3d9cfb37a5/href</a></iframe><p>Notice we have two useEffects inside our component. The first one takes a callback that simply sets our state after a faked asynchronous request (using setTimeout). Let’s pretend we used this one to make a call to our database to get back our user’s information. In the real world, we’re not sure exactly how long it’ll take, so we send the request, and then the component re-renders after the data is returned. We pass it an empty array to signify it should run once at startup, and then no more.</p><p>The second useEffect however, will fire once at component mount, and then again if there’s a change to the “username” piece of state. Notice what happens when you click “change name” (aside from making the Cool Guy’s name cooler) — the name change counter increments. This is because the second useEffect is ready to enact its changes whenever “username” changes. This also explains why when you load this CodePen, it will move up to 2 from 0. It moves from 0–1 when the name variable is initialized and the component mounts, and then again once “Cool Guy” is “loaded from the DB.” Also notice how clicking “Get New Lucky Number” does not incur changes in the name counter though it also is changing state and forcing a component rerender.</p><p>The last important thing to mention about useEffect is that it also includes some of the functionality of “componentDidUnmount” in the form of a return. If you define a function inside of useEffect (such as an event listener), and then at the end of the original useEffect callback, return that named function, React will clean up and remove your event listener.</p><h3>UseRef()</h3><p>A less common hook that you may find yourself in need of is the “useRef” hook. Because React is creating, rendering, and updating a virtual DOM which informs the actual browser DOM, it makes it difficult to reliably access specific nodes using methods like “document.getElementById’. The solution? useRef! UseRef allows for the persistence and potential changing of a value, without triggering a component re-render. useRef can be used to access specific nodes and set their values by passing a “ref” attribute to an element, with the value of that attribute being the created reference. Importantly, the value of the node is stored on the “current” property of the reference you create. It is through this current property that you can access the actual DOM node React is creating. See the code below for an example.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fjoetoenails%2Fembed%2Fpreview%2FmdOVBVp%3Fheight%3D600%26slug-hash%3DmdOVBVp%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fjoetoenails%2Fpen%2FmdOVBVp%3Feditors%3D0011&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/61e849d5264572f5b59cbe3ae8b8fa4a/href">https://medium.com/media/61e849d5264572f5b59cbe3ae8b8fa4a/href</a></iframe><p>It may seem simple, but what we’re doing in this example is editing the <strong>actual </strong>DOM, not the virtual one created by React behind-the-scenes. References allow us to manipulate elements without triggering component re-renders. Notice how we’re tapping into the “style” attribute of the input field in order to manipulate the “display” property. And all this is being done on the “current” property of the reference.</p><p>Some instances where references might be useful include:</p><ul><li>Websockets — often when a component re-renders, it may trigger a reset of a websocket connection, thus breaking an existing connection and generating a new one. Storing your socket invocation/creation in a reference would prevent this connection from being severed if there are changes to a component upon mounting, or if there are changes to state.</li><li>Video: Often, video streams need to be placed upon a waiting video element. We may need to wait for the stream to become available, or make changes to state (pausing the video, scrubbing through it, etc), and either of these may cause the entire stream to quickly “blink” as a component re-renders. However setting the stream as a reference can help this data persist despite other changes to the component.</li><li>Keeping track of previous states. Say for some reason you needed to keep track of a previous state (an undo button perhaps?). A reference value can help keep that information around after it’s no longer active on state.</li><li>Preventing information from loading on a component’s initial render (but rendering upon other updates) as seen <a href="https://stackoverflow.com/questions/55075604/react-hooks-useeffect-only-on-update">here</a>.</li></ul><h3>useContext()</h3><p>The last major hook we’ll talk about is useContext(), and in order to use it, you’ll need a quick refresh of <a href="https://reactjs.org/docs/context.html">React Context</a>. I suggest going to the documentation here, but long story short is that Context allows for the creation of variables that are accessible from any component in your app provided you have a “Provider” component surrounding it. Interestingly, this is exactly how the Redux store is implemented in most React apps. You have a &lt;Provider&gt;, offering a “store” prop to any child component. Some people say Context and Hooks may even <a href="https://blog.logrocket.com/use-hooks-and-context-not-react-and-redux/">replace Redux one day…</a>)</p><p>But how do I easily access that context from deeply nested components? Yep, you guessed it, useContext! useContext takes one parameter — the React context object you’ve created using React.createContext().</p><p>Let’s say you’ve created an object that stores various button sizes:</p><pre>buttonSizes={<br>  small:{<br>    width:200px,<br>    height:200px<br>  },<br>  large:{<br>    width:600px,<br>    height:600px<br>  }<br>}</pre><p>We then can create a Button Context that taps into those variables like so:</p><pre>const buttonContext = React.createContext(buttonSizes.small)</pre><p>Note, the sole parameter of createContext is simply the default value for this context, and in the snippet below, we’re overriding that default. Now let’s wrap some components in our ButtonContext provider.</p><pre>function App() {<br>  return (<br>    &lt;ButtonContext.Provider value={buttonSizes.large}&gt;<br>    &lt;UserSignUp /&gt;<br>    &lt;/ThemeContext.Provider&gt;<br>  );<br>}</pre><p>Now, any components nested inside of ButtonContext.Provider (including UserSignUp, and all its children), can access the provided Button size context, without having to pass down the size as a prop over and over again. Inside of the component where you’d like access to the button sizes, simply invoke useContext like so:</p><pre>const buttonSize = useContext(ButtonContext)</pre><p>Now, buttonSize will correspond to “large” since that’s the value being provided by the provider component. It’s worth mentioning that you may need to export and import your context information if your components are in different files.</p><p>This is the simplest implementation of context, however it can be used to persist and access a lot of useful information. For example, in our project <a href="https://two-plus.web.app/userhome">Two Plus</a>, our team created an Auth Context that provided a logged in user’s information across all components. By wrapping a useContext hook inside of another exported function, we were able to create our own custom hook that enabled us to access the many “value” variables that exist on our context provider just by calling “useAuth()”. <a href="https://github.com/MasterCodersInc/TwoPlus/blob/main/src/contexts/AuthContext.js">Feel free to check out our code for a more in-depth look.</a></p><h3>Other less common, but equally useful hooks…</h3><h4>useParams()</h4><p>useParams won’t be found in the core React code, but can be found as an import from the very popular ReactRouter library. If you’re using React Router to define front-end routes of your single-page-application, useParams takes the place of the confusingly-named `props.match.params` object. You can use ‘useParams()’ to quickly and easily extract information you’d need from any url.</p><p>For example, Public Profile components may exist at “/users/:profileID”, and simple destructuring allows you to easily grab those wild-card components that live in your URL and use them in your component.</p><pre>export function <strong>PublicProfile</strong>() {<br>  const { profileID } = <strong>useParams</strong>();</pre><pre>return (...JSX...)<br>}</pre><h4>useHistory()</h4><p>useHistory is another hook that exists within the React Router library. It allows you to easily grab the powerful history instance that React Router creates when a component exists in a route. When you build your component, simply add a line like:</p><pre>const history = <strong>useHistory</strong>()</pre><p>And you’ll be able to modify navigation around your site easily. For example, clicking the button below would trigger a route change for a user.</p><pre>&lt;Button<br>   <em>onClick</em>={() =&gt; {history.<strong>push</strong>(`/users/${profileUID}/followers`)}}<br>&gt;<br>Go to Followers<br>&lt;/Button&gt;</pre><p>For even more hooks inspiration, I recommend checking out the myriad of custom hooks that other users have made. They can be used from everything from making asynchronous API calls to acting as a simple toggle switch. <a href="https://github.com/stevenpersia/captain-hook">Captain Hook’s library is a great place to start.</a></p><p>I hope you’ve found this intro to React’s hooks helpful, and you can start to see the similarities in how they’re created or invoked, and the differences in their functionality. Now get out there and useHooks! Or if you’re feeling super ambitious, <a href="https://reactjs.org/docs/hooks-custom.html">make some of your own!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e4b131f5535" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>