<?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 Zethembiso Msomi on Medium]]></title>
        <description><![CDATA[Stories by Zethembiso Msomi on Medium]]></description>
        <link>https://medium.com/@Zjybra?source=rss-192aa1122d48------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*6HO00imJWtz8L8oY.jpg</url>
            <title>Stories by Zethembiso Msomi on Medium</title>
            <link>https://medium.com/@Zjybra?source=rss-192aa1122d48------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 15:04:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Zjybra/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[React Bits: React Memoization]]></title>
            <link>https://medium.com/@Zjybra/react-bits-react-memoization-9e2b917042f4?source=rss-192aa1122d48------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e2b917042f4</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-usememo]]></category>
            <dc:creator><![CDATA[Zethembiso Msomi]]></dc:creator>
            <pubDate>Wed, 01 Mar 2023 22:06:05 GMT</pubDate>
            <atom:updated>2023-03-01T22:06:05.178Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, we are going to be discussing the <strong>useMemo</strong> &amp; the <strong>useCallback </strong>hooks. What these hooks are all about and how to make use of them.</p><p>In React applications you would typically have a tree of components representing the UI. When an action, such as a state update, happens it normally causes the whole tree to be re-rendered.</p><p>This intrinsically isn’t a bad thing and requires that we pay attention to what each of the components in the tree does as part of its rendering process.</p><p>There are two things that we would need to pay attention to in that analysis.</p><p>1. Is the component’s render process expensive, computationally or otherwise? Are we doing some intense calculations with data like looping over large arrays or computations that have side effects beyond the boundary of the immediate area of concern?</p><p>2. Are we making network calls?</p><p>These questions are necessary to answer prior to applying any optimization as we do not want to naively apply optimizations where their net effect is going to be negligible.</p><p>In the instance that we do find that the re-renders of the component tree have hot spots of performance bottlenecks that degrade the User Experience, we can then start looking into what can be done to control those re-render processes for an optimal User Experience.</p><p>One such optimization is the use of Memoized components.</p><p>What are memoized components?</p><p>Memoized components are components that are created with the use of the <strong><em>React.memo(…)</em></strong> Higher Order Component.</p><p>Let’s quickly define a few terms that we have used already.</p><p>Those are <strong><em>Memoized Component</em></strong> and <strong><em>Higher Order Component</em></strong>.</p><p>Let’s start with Higher Order Components.</p><p>These are components that produce/make/enhance other components. These look and behave like typical components, their distinguishing feature is that they accept a component as a parameter and wrap it with JSX and/or other behaviour.</p><p>The other term is Memoized Component. With this term, our only interest is in Memoization. Which is an optimization technique that deterministically returns a given output for a particular set of inputs.</p><p>An example of this is that, if you have a bunch of ID values and you want to get data from an API for each of them, when you supply the same id to a memoized function, you will only make the API request once and all subsequent requests will not go to the API because we already have the result.</p><p>Now, to put all this together.</p><p>Memoized Components, using <em>React.memo(…),</em> function under a similar premise. <em>React.memo(…)</em> is a Higher Order Component that adds memoization behaviour to the supplied component. What that means in the context of React is that the memoized component will not re-render when its inputs (props) have not changed.</p><p>That sounds fantastic!</p><p>React.memo FTW!</p><p>Memoize everything, right?!</p><p>Well, like all things, it depends…</p><p>We already understand that some components might be computationally expensive or make use of expensive resources. This doesn’t mean that we should immediately reach for React.memo.</p><p>We could start our optimization effort at the source of the expense.</p><p>Still using memoization, the principle of the technique itself, we could implement some caching mechanism for the computation or network requests in question.</p><p>But returning to React specifically, how do we decide when to use React.memo?</p><p>Let’s walk through how React works especially the fundamental problem it solves to better understand the process around this kind of decision.</p><p>At the heart of web applications is taking data and transforming it into some representation on the UI. Part of that exercise involves working with the DOM to build the UI.</p><p>In the days of JQuery and other things that shall not be named (cough, Angular) since we took the data and passed it through some Javascript and made calls to manipulate the DOM to build the UI.</p><p>Now, this all worked, but there were a few things that in today’s world make these experiences undesirable. This can be summed up in the fact that every change we made to the data through Javascript is always headed for the DOM and the process that the browser must go through to build the UI from those DOM updates.</p><p>Thinking about this for a moment, it was common to come across code that didn’t have a purpose to the task that the user needs to accomplish but was for the purpose of DOM management, at least such code would be seen in codebases where developers cared about the impact of updating the DOM.</p><p>Although in practice, the browsers are very efficient in executing their internal processes. It is still better to avoid initiating them unnecessarily in the first place. As this prevents slow and sluggish behaviour that comes as a cost of these overhead computations.</p><p>Where React’s improvement comes with their introduction of the Virtual DOM, which is an in-memory representation of the actual DOM that is your UI. The React runtime is then responsible for handling the UI updates and applying them first to the VDOM, doing a comparison between the VDOM and the actual DOM and only applying the necessary differences if there are any.</p><p>Now, back to how to decide when to use React.memo.</p><p>What we need to understand first about React.memo is that it works better with primitive values for props. So simple things like booleans, strings, and numbers. It doesn’t work so well with objects and arrays.</p><p>Well, why is that?</p><p>This is because React only does a shallow comparison of the props.</p><p>This is for the sake of efficiency that would be lost when doing deep comparisons by looking into complete object graphs and logarithmic complexities that would arise from inspecting things like arrays.</p><p>This is also due to the fact that objects and arrays are not received as values but rather as references.</p><p>So when that comparison check happens, it isn’t happening on the values themselves (contents of the object or array) but rather on the references to those things, which are always going to be different even though underneath they are essentially the same.</p><p>So, best to stick with primitives and be mindful of what passing non-primitive values as props could potentially mean.</p><p>If you absolutely MUST pass the prop as either an object or array, then there are two options available to you.</p><p>First, you will need to pass your own comparison mechanism as a second parameter to React.memo like this:</p><pre>const MyMemoedComponent = React.memo(MyComponent, (prevProps, nextProps) =&gt; {<br>  // NOTE: Be very efficient with your comparisons here as it affects your application&#39;s user experience.<br>  return prevProps.something_I_care_about === nextProps.something_I_care_about;<br>})</pre><p>The other option would be to memoize the prop object that is passed into your memoized component like this:</p><pre>const params = React.useMemo(() =&gt; ({color:swatchColor}), [swatchColor]);<br>return (<br>  &lt;&gt;<br>    &lt;MyMemoedComponent params={params} /&gt;<br>  &lt;/&gt;<br>);</pre><p>You will notice that we’re still passing in the prop as an object. From what we have already discussed, this should not work because objects are passed by reference.</p><p>So why is this working now?</p><p>The reason it is working is that the ```useMemo(…)``` hook we have used to memoize the value for the params prop, will return to us the same reference for a given input in the dependencies array.</p><p>This then means, that the comparison in ```React.memo(…)``` will be working with a stable reference and thus preventing unnecessary re-renders.</p><p>Now, knowing all of this, where and when do we use ```useMemo(…)```?</p><p>In the next article, we will explore this question with examples.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e2b917042f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>