React Hooks and how to adopt

Flávio Juvenal
February 28, 2020
<p><a href="https://reactjs.org/docs/hooks-intro.html">Hooks was a new addition to React that came in version 16.8.</a> It was an new exciting feature because it would allow us to have flexibility when dealing with components' internal state, lifecycle code, Context API, and other React features.</p><p>Before that, developers only had one place for state in React components: <code>this.state</code>. Even if you have different, unrelated data, they needed to be at the same place, which makes it hard to apply the concept of code colocation – related code should be as close as possible. Working with component lifecycle logic also has the same issue. <code>componentDidMount</code>, <code>componentDidUpdate</code>, and <code>componentWillUnmount</code> may contain unrelated code, which makes components harder to maintain. Another complication was working with Context Consumers. It had a lot of boilerplate, because it used either <a href="https://reactjs.org/docs/higher-order-components.html">Higher Order Components</a>, or <a href="https://reactjs.org/docs/render-props.html">Render Props</a>, and it could get out of hand very quickly if <a href="https://reactjs.org/docs/context.html#consuming-multiple-contexts">you had to consume from a lot of Providers</a>.</p><p>With the new tools Hooks provides us, we can have more granularity of state and lifecycle logic. And not only that! We can also<strong> abstract and reuse</strong> that logic, something that wasn't quite possible before with class components!</p><p>I recommend watching <a href="https://www.youtube.com/watch?v=dpw9EHDh2bM">this video</a> from React Conf 2018, where they announced Hooks for the first time. It explains the motivation of the React team, and also some introduction and examples of the new feature. <a href="https://twitter.com/prchdk/status/1056960391543062528">This animation</a> that uses code from the previous video shows very clearly how Hooks can help us solve the problem of colocation.</p><h2 id="basic-react-hooks">Basic React Hooks</h2><p>The <a href="https://reactjs.org/docs/hooks-overview.html">React documentation does a great job explaining how to use the new Hooks</a>, and also some <a href="https://reactjs.org/docs/hooks-rules.html">new rules that you need to follow</a> to make sure everything works as expected. Since there's already a lot of accessible information about them, I'll just have a summary here:</p><h3 id="usestate">useState</h3><figure class="kg-card kg-code-card"><pre><code class="language-javascript">const [state, setState] = useState(initialState);</code></pre><figcaption>Returns a stateful value, and a function to update it.</figcaption></figure><p>Your state here can be any data; there's no need to be an object. You should use multiple <code>useState</code> calls for different, unrelated data. </p><h3 id="useeffect">useEffect </h3><figure class="kg-card kg-code-card"><pre><code class="language-javascript">useEffect(callback, depArray);</code></pre><figcaption>Accepts a function that contains imperative, possibly effectful code.</figcaption></figure><p><a href="https://reactjs.org/docs/hooks-effect.html">This Hook is used to run code based on lifecycle phases.</a> It's also used to run side effects when a set of given dependencies change – this might be props, or data from other Hooks, like context and state. On top of that, it allows adding cleanup logic for those effects in an easy way. This is very useful to simplify the previous method of listening to prop changes, with <code>componentDidUpdate</code> and <code>prevProps</code>. </p><p>Here's an example. Suppose you want to do some action after another one, but you only have access to a status prop that might be <code>pending</code>, <code>finished</code> or <code>error</code>. You could do it like this:</p><pre><code class="language-javascript">class Component extends React.Component { componentDidUpdate(prevProps) { if (prevProps.status != this.props.status &amp;&amp; this.props.status === 'finished') { doSomething(); } } }</code></pre><p>With <code>useEffect</code>, it becomes:</p><pre><code class="language-javascript">const Component = ({ status }) =&gt; { useEffect(() =&gt; { if (status === 'finished') { doSomething(); } }, [status]); };</code></pre><p>Besides the documentation, I also really like <a href="https://wattenberger.com/blog/react-hooks">this link</a> that explains how <code>useEffect</code> works. It isn't only a way of doing lifecycle logic. It does change the way you code those side effects.</p><p>A quick example would be something like a paginator component. Usually, you need to fetch data: 1) when it mounts; 2) when a page changes. You may implement this like: when the user clicks the next page button, update the page state, and then call the method that fetches data. If you use <code>useEffect</code>, you can bind the effect to the page state, and then, the next page button click handle only needs to update the state: fetching the data would come automatically. With this, further logic that updates the page state also updates the data, which is convenient. This case is a simple example, but the applications are endless.</p><h3 id="usecontext">useContext</h3><figure class="kg-card kg-code-card"><pre><code class="language-javascript">const value = useContext(MyContext);</code></pre><figcaption>Accepts a context object (the value returned from <code>React.createContext</code>) and returns the current context value for that context.</figcaption></figure><p>This Hook is handy because it makes very easy to consume contexts without nesting your JSX. Also, it opens a lot of possibilities when using custom Hooks.</p><h3 id="usereducer">useReducer</h3><figure class="kg-card kg-code-card"><pre><code class="language-javascript">const [state, dispatch] = useReducer(reducer, initialArg, init);</code></pre><figcaption>An alternative to <a href="https://reactjs.org/docs/hooks-reference.html#usestate"><code>useState</code></a>. Accepts a reducer of type <code>(state, action) =&gt; newState</code>, and returns the current state paired with a <code>dispatch</code> method. (If you’re familiar with Redux, you already know how this works.)</figcaption></figure><p>If you notice your <code>setState</code>'s are changing at the same time, you may use <code>useReducer</code> to group up related data.</p><h3 id="usecallback-usememo">useCallback / useMemo</h3><figure class="kg-card kg-code-card"><pre><code class="language-javascript">const memoizedCallback = useCallback( () =&gt; { doSomething(a, b); }, [a, b], );</code></pre><figcaption>Returns a <a href="https://en.wikipedia.org/wiki/Memoization" rel="nofollow noopener noreferrer">memoized</a> callback.</figcaption></figure><p>If you used Pure Components before, you probably noticed that keeping your references from changing is necessary to optimize some components. Since you redefine a callback every time a functional component renders, <code>useCallback</code> is used to keep this reference unchanged.</p><figure class="kg-card kg-code-card"><pre><code class="language-javascript">const memoizedValue = useMemo(() =&gt; computeExpensiveValue(a, b), [a, b]);</code></pre><figcaption>Returns a <a href="https://en.wikipedia.org/wiki/Memoization" rel="nofollow noopener noreferrer">memoized</a> value.</figcaption></figure><p><code>useMemo</code> is related to that, but not the same. It is used to avoid recomputing expensive calculations or rendering expensive components. Do not use this for side effects – <code>useEffect</code> is the right one –, the explanation for that is present in the <a href="https://reactjs.org/docs/hooks-reference.html#usememo">documentation</a>:</p><blockquote>You may rely on useMemo as a performance optimization, not as a semantic guarantee. 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. Write your code so that it still works without useMemo — and then add it to optimize performance.</blockquote><p>You may think you need to use it frequently, but it might not be that necessary. For a better explanation, there's this <a href="https://kentcdodds.com/blog/usememo-and-usecallback">fantastic article from Kent C. Dodds</a> explaining when to use each of them.</p><h3 id="useref">useRef</h3><figure class="kg-card kg-code-card"><pre><code>const refContainer = useRef(initialValue);</code></pre><figcaption><code>useRef</code> returns a mutable ref object whose <code>.current</code> property is initialized to the passed argument (<code>initialValue</code>). The returned object will persist for the full lifetime of the component.</figcaption></figure><p><code>useRef</code> works similar to <code>useState</code>, except it does not trigger rerenders. You can use it to hold into any value. Very useful to store callback references like <code>setTimeout</code>, etc.</p><h3 id="remaining-hooks">Remaining Hooks</h3><p>These are some of the commonly used Hooks. Others are used more situationally. Learn more about them in the <a href="https://reactjs.org/docs/hooks-reference.html">official docs</a>.</p><h2 id="third-party-hooks">Third-party Hooks</h2><p>A lot of your current code can also benefit from the new feature. Probably the libraries that you use already supply their own custom Hooks. Here are some examples:</p><p><a href="https://reacttraining.com/react-router/web/api/Hooks">React Router</a> has <code>useHistory</code>, <code>useLocation</code>, <code>useParams</code>, and <code>useRouteMatch</code>. <a href="https://react-redux.js.org">React-redux</a> has <code>useSelector</code> and <code>useDispatch</code>. <a href="https://jaredpalmer.com/formik/docs/overview">Formik</a> has <code>useField</code>, <code>useFormik</code> and <code>useFormikContext</code>.</p><p>We also have new possibilities, <a href="https://github.com/zeit/swr">SWR</a> and <a href="https://github.com/tannerlinsley/react-query">react-query</a> comes to mind. For more examples about Hooks, look at the <a href="https://github.com/rehooks/awesome-react-hooks">awesome-react-hooks</a> repository and the <a href="https://usehooks.com">useHooks</a> website.</p><h2 id="custom-hooks">Custom Hooks</h2><p>For me, this is the most impactful change: the possibility of using Hooks – either the react ones, or from a library – in a <strong>reusable </strong>way. This level of reusability is not possible with class components.</p><p>You will likely have some business logic code that can be implemented with Hooks. Don't be afraid of extracting this logic to a Custom Hook.</p><p>On our project, we have the <code>currentUser</code> object in the redux store. We would access this with <code>mapStateToProps</code>. It had some boilerplate code, but then we thought it was simpler just to create a <code>useCurrentUser</code> that uses <code>useSelector</code> from <code>react-redux</code> library, and that's it – straightforward yet valuable change. We also have <code>useToggles</code> for feature toggles and <code>usePermissions</code> for permissions.</p><p>Another useful example for us is that some pages have an <code>origin</code> parameter in its query string, and we would use this URL to go back after a form submit, for instance. We could use <code>useLocation</code> from React Router and extract this logic.</p><pre><code>export function useOriginRoute(defaultRoute) { const location = useLocation(); const args = parse(location.search); // from 'query-string' let route = defaultRoute; if (args.origin) { route = args.origin; } return route; }</code></pre><p>Custom Hooks are the game-changer here. Look for opportunities for them in your application; you won't regret it.</p><h2 id="adoption-steps">Adoption steps</h2><p>After learning about React Hooks, your first thought would probably be: "Hey, this thing might be awesome for my team! I want to bring this to my project ASAP". I was also excited to start using Hooks in production right away. </p><p>Perhaps you already have a team member as excited as you, or your tech leader has already heard about React Hooks and wants to push it to the project. That makes everything easier, but if this is not your situation, you need to tackle this subject with caution.</p><p>Although coding with Hooks sounds more straightforward than the standard class components, it is not trivial to be picked up, even for experienced developers. Using them out of nowhere in your pull requests might actually slow your team down. Here at Vinta, I took the safe approach to make sure my team was aware of how this new feature works, to keep everyone on the same page, and to minimize the overhead for them. Here's what I did:</p><h3 id="update-react-version">Update React version</h3><p>First of all, you are to update your React version to 16.8+. Probably this is not an issue if you work in a recent project – React 16 was launched in September 2017. Otherwise, you have to work a little bit on updating React and any other dependencies that might break with this update.</p><h3 id="study-a-lot-about-hooks">Study (a lot!) about Hooks </h3><p>You might have read a few articles, seen some buzz on Twitter, and checked some Github gists with Hooks magic. But these wouldn't be enough. You need to understand the motivation behind it: learn the quirks of <code>useEffect</code> and its array of dependencies; why rules of Hooks are essential; when to use <code>useCallback</code> or <code>useMemo</code> (or neither). </p><p>Take some time to read the documentation, as well as to look for extensive articles with plenty of Hooks examples, in order to fully grasp the concept of it. Working in a playground app is very important too. You need to be ready to show your team why Hooks can make everyone's life easier.</p><h3 id="introduce-the-idea-to-your-team">Introduce the idea to your team</h3><p>Before proceeding, meet with your manager/tech lead. Talk to them about Hooks. Explain that you believe it will be awesome to have it on the project. Let them know it's a feature that could be adopted gradually. Also, make sure they understand you will have the ownership of teaching the team about the tool, good practices with it, and its pitfalls. After that, do a quick presentation about Hooks to your co-workers. It doesn't have to be detailed: Give a brief introduction, show them the documentation. They don't need to learn everything now, just having a gist of it is enough.</p><h3 id="update-3rd-party-libraries-that-use-hooks">Update 3rd party libraries that use Hooks</h3><p>Some widely used React libraries got cool Hooks that give a lot of benefits. Like React Router, React Redux, and others. Using these Hooks in new code, or refactoring old code with them, might be a great example to show your team how this can simplify the codebase.</p><h3 id="find-a-use-case">Find a use case</h3><p>Now that your teammates have some knowledge about Hooks, you can start finding some situations in your project where using them would be beneficial, so later, you can have some examples for them to use. Using the Hooks from React are cool, but too simple. We are looking for some nice use cases for a custom Hook. For instance, mine was a Hook to check if some specific DOM node had ellipsis, so we could add a tooltip only on elements that had ellipsis.</p><pre><code class="language-javascript">export function useEllipsisCheck() { const [hasEllipsis, setHasEllipsis] = useState(false); const nodeRef = useCallback((node) =&gt; { if (node != null &amp;&amp; node.scrollWidth &gt; node.offsetWidth) { setHasEllipsis(true); } }, []); return { hasEllipsis, nodeRef }; }</code></pre><p>Very simple yet effective Hook, it made our ellipsis check logic way cleaner, and reusable! Another good example is to use a custom Hook to abstract the usage of 3rd party Hooks. Have a repetitive logic with React Router props? Replace it with a custom Hook!</p><h3 id="teach-your-colleagues">Teach your colleagues</h3><p>Once you start using Hooks and creating custom ones, your peers will learn a lot reviewing your pull requests, but they still might need a hand. Good descriptions and relevant comments can help with this process. Also, offer to pair programming with them when you notice an opportunity of using Hooks in their task. This is the moment they'll really notice the value of using Hooks in the code.</p><h3 id="success-">Success!</h3><p>Awesome! At this stage, your team should be using Hooks comfortably. As time goes on, the team will find opportunities to use custom Hooks to reuse a lot of logic, either while refactoring old code or new. The cool thing about Hooks is that you can approach the same problem you had before from a new point of view, since now you have more flexibility to handle it. Don't be afraid of trying something new; it will probably be worth it in the long run.</p><h2 id="conclusion">Conclusion</h2><p>In this article, I've briefly introduced the concept of React Hooks, how it can change the way you code your React components, how libraries can help with that, and my experience introducing this new feature to my colleagues at Vinta.</p><p>Have something I missed but you think it's important? Want to share your experience with React Hooks? Is there something you want to ask about? Let me know in the comments!</p>