<?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 Alex Park on Medium]]></title>
        <description><![CDATA[Stories by Alex Park on Medium]]></description>
        <link>https://medium.com/@apark0720?source=rss-15d06b84a38d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*nkxWsplJ7uKGsihLiCvQ-w.jpeg</url>
            <title>Stories by Alex Park on Medium</title>
            <link>https://medium.com/@apark0720?source=rss-15d06b84a38d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 09:04:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@apark0720/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[The Definitive Guide to React Class vs Functional Components.]]></title>
            <link>https://javascript.plainenglish.io/the-definitive-guide-to-react-class-vs-functional-components-481b1157ed08?source=rss-15d06b84a38d------2</link>
            <guid isPermaLink="false">https://medium.com/p/481b1157ed08</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alex Park]]></dc:creator>
            <pubDate>Mon, 24 Feb 2020 19:50:30 GMT</pubDate>
            <atom:updated>2020-02-27T01:15:34.637Z</atom:updated>
            <content:encoded><![CDATA[<p><em>**The following information is a summary of information from Dan Abramov, Sophie Alpert, and the React docs.**</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NwQQN_YPRu7QskBM.png" /></figure><h3>A. DEMO: The main problem with class components</h3><p>Please open this codesandbox link to the side: <a href="https://codesandbox.io/s/classvsfunctional-0g863">https://codesandbox.io/s/classvsfunctional-0g863</a> and perform the following actions:</p><ol><li>In Dan’s Profile, <strong>click</strong> the “Follow (class)” button.</li><li>Within 3 seconds, <strong>change</strong> the user profile to Sophie by using the dropdown at the top of the page.</li><li>The alert text <strong>incorrectly </strong>reads “Followed Sophie.”</li></ol><p>If you repeat the above steps with the “Follow (functional)” button, the alert text should <strong>correctly</strong> read “Followed Dan.” <br> <br> Let’s look closely at the showMessage method in our class component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*cSSgONSYkzZKAkdydjpXVw.png" /></figure><p>This class method reads from this.props.user. Props should be treated as immutable in React, and should not be mutated directly. However, this in JavaScript has always been mutable. If you go back to the codesandbox example and view the constructor in ProfilePageClass.js, you will notice that the this context of the showMessage function has already been bound (so that is not the cause of the bug). The problem occurs when a class component re-renders before a request that is bound to the this context of the class component is complete. The showMessage callback is not tied to any particular render and thus loses the correct props.</p><h3>This problem can be solved in two ways:</h3><p><strong>Option 1)</strong> Readthis.props early, and explicitly pass the extracted value to the callback function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*7T28tlr6KRNt4WZqxCOV1g.png" /></figure><p>However, this approach makes the code more verbose and adds complexity especially if the showMessage function also calls a different function contained in this.props. <br> <br> <br> <strong>Option 2)</strong> Use closures to capture the props at the time of render:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*5KdanLgqMdS_vMD2PkwFiA.png" /></figure><p>This way any code inside it (including showMessage) is guaranteed to see the correct props for that particular render. If we simplify the code by removing the class “shell” around it, it becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*sPf9zt9P2_ssfAKNC-kefQ.png" /></figure><h4>The biggest difference between class and functional components is that functional components capture the props at render time.</h4><p>In order to use <strong>stateful</strong> functional components, React 16.8+ and the use of React Hooks are required.</p><h3>B. Advantages of using Hooks for stateful components</h3><h4>1) Avoid unnecessary nesting of the component hierarchy</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*B4OgEw-tB51pH0qxVL3Ung.png" /></figure><p>The main patterns to share code across components in (vanilla) React are a combination of the Context API, higher-order components, and render props patterns. These patterns are great for some cases but come with the downside of having to restructure your components in order to use them. In more complicated cases, this leads to “wrapper hell” where the component tree becomes very nested. This makes it difficult to follow the data flow through the app.</p><p>The code snippets below, show a side-by-side comparison of common use cases of class and functional components where the theme and locale are provided to the component. In the class component example, an additional layer of nesting occurs each time we access the theme and locale through the Context.Consumer (which will repeat across components throughout the application). Whereas in the functional component example, there is no nesting as we can now use theuseContext hook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*AyBK2204KaDmahGBs81KwQ.png" /></figure><h4>2) Easier to reuse logic across components</h4><p>Class components manage side effects through lifecycle methods. Because of this, each individual task has to be split up across different life cycle methods. In comparison, we can group side effects by functionality for functional components.<br> <br> <em>Class component example of managing side effects:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*kKODQTgGEUD_gyBsEocFIg.png" /></figure><p>A couple of things to note:</p><ul><li>the code for setting and updating document.title is repeated because class components force us to split logic across component life cycles.</li><li>in componentDidMount() we have two unrelated methods, making it more difficult to test them in isolation.</li></ul><p><em>Functional component example of managing side effects:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*6kr_qZtTYx6fJ9k7ckG4Mw.png" /></figure><p>Through use of hooks and grouping our side effects by functionality, the above two problems become resolved. Furthermore, because useEffect() is simply a function, <strong>we can now extract it and create a custom hook to reuse across components.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*fO04B7PVcIsKRQ14pYVazw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*rEapW0yrvdQmupJUQeI-Sg.png" /></figure><p>Through hooks, we can also extract and reuse common event handlers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*_B2aLTtE0hyQ3P4iLbr1pQ.png" /></figure><p>After extracting them, we can now use them inside functional components like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*V_3M1aSDVO3De55NEug-NA.png" /></figure><h4>3) Less overhead for both developers and compilers</h4><p>With the use of functional components, developers do not need to worry about capturing props at render time as mentioned in the first section, nor about thethis context changing and having to bind it. Also,<strong> the React compiler cannot fully optimize class components the way it can optimize functional components</strong>. While the performance difference is not significant, it can add up as the code base grows. Other things to note is that the React compiler cannot fully minify class components and that hot-reloading can be less reliable for class components.</p><h3>C. Other considerations</h3><p>1) Hooks cover the vast majority of common use cases for classes. There are no equivalents for getSnapshotBeforeUpdate() or componentDidCatch lifecycle methods as of yet, but the React team is working to include them in the near future.<br> 2) Some third-party libraries might not be compatible with Hooks at the moment. But, most widely used libraries have hooks support and because class components and functional components can be used in the same application, this will likely not be an issue.<br> 3) In functional components, all function declarations are re-created upon re-render, whereas in class components the functions are stored in the class’s prototype. This is a negligible performance difference, and the overall performance of functional components is slightly better than class components (even this is very small, performance is not the main advantage of using hooks).</p><h4>Recommendation: for new development use functional components in lieu of class components for the following reasons:</h4><ul><li>capture props at render time</li><li>flatter component hierarchy tree and simpler component code</li><li>easily reuse logic across components through custom hooks &lt;= biggest benefit</li></ul><p>For an existing codebase, it is <strong>not a high priority</strong> to convert class components to functional components besides the standardization of the codebase.</p><p>For more information:</p><ul><li><a href="https://overreacted.io/how-are-function-components-different-from-classes/">https://overreacted.io/how-are-function-components-different-from-classes/</a></li><li><a href="https://www.youtube.com/watch?v=dpw9EHDh2bM">https://www.youtube.com/watch?v=dpw9EHDh2bM</a></li><li><a href="https://reactjs.org/docs/hooks-faq.html">https://reactjs.org/docs/hooks-faq.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=481b1157ed08" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/the-definitive-guide-to-react-class-vs-functional-components-481b1157ed08">The Definitive Guide to React Class vs Functional Components.</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Utilize the useReducer and useContext Hooks to Mimic Redux Architecture]]></title>
            <link>https://medium.com/@apark0720/how-to-utilize-the-usereducer-and-usecontext-hooks-to-mimic-redux-architecture-w-real-app-example-f6ba1e00329d?source=rss-15d06b84a38d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6ba1e00329d</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react-context]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Alex Park]]></dc:creator>
            <pubDate>Mon, 17 Jun 2019 13:01:02 GMT</pubDate>
            <atom:updated>2019-09-24T01:59:16.578Z</atom:updated>
            <content:encoded><![CDATA[<h4>A walkthrough with a real-world example</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bWuDdSLfL9Q6HUt4.jpg" /></figure><p><em>The repo for this piece can be found at </em><a href="http://github.com/spearmintjs/spearmint"><em>https://github.com/spearmintjs/spearmint</em></a><em>.</em></p><p>You might have heard by now that you can utilize the useReducer and useContext Hooks in place of Redux. When I wanted to try it out for myself, I found it difficult to find resources that were using Hooks and Context for a substantial application. This post will walk you through how to use Hooks and Context for complex shared state with a real-world example.</p><p><em>Disclaimer: This post assumes intermediate knowledge of React and Redux.</em></p><p>The example application we are going to use is <a href="http://www.github.com/spearmintjs/spearmint"><strong>spearmint</strong></a>: an open-source tool to help developers easily create functional React tests without writing any code. It dynamically converts user inputs into executable Jest test code by using DOM query selectors provided by the react-testing-library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ac-ppALQhN5p7T8h" /><figcaption>Spearmint is in beta — star us to keep tabs on our progress!</figcaption></figure><p>Though there are multiple useReducer and useContext hooks in this application, I will be walking through the testCase reducer and how its state was shared across multiple components.</p><p>Before we start diving in, I’ll provide a high-level overview of what the testCase reducer is doing. The testCase component is the panel you see in the middle and the testCase reducer stores all the state for user-inputted render, action, and assertion statements. When we click the export button on the NavBar component, the ExportFileModal component gets triggered. Once the user clicks the save button on the modal, we useContext to access the state from the testCase reducer in order to generate the test file.</p><h3>Step 1: Action Constants, Action Creators, Reducer</h3><p>This part is easy: You write these the exact same way you would if you were to use the Redux library. I will only embed an abbreviated version with three actions here. You can view the full code for the <a href="https://github.com/apark0720/spearmint/blob/master/src/context/testCaseActions.js">testCaseActions.js</a> or <a href="https://github.com/apark0720/spearmint/blob/master/src/context/testCaseReducer.js">testCaseReducer.js</a> if you want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B-29TNVbuPXjDXtMu6iaTg.png" /></figure><p>The only thing to note is line 4 of the testCaseReducer.js file where we createContext for the testCase. We do not want to provide it a default value, thus we pass in null as the argument. Note that you do not have to createContext in the reducer file and can createContext in the component where you use the Provider (in our case, App.jsx). Because we had multiple contexts, our App.jsx was getting messy and chose to move the createContext calls to each respective reducer file.</p><p>Let’s look at how to share reducer state with useReducer and Context Provider in the next session.</p><h3>Step 2: useReducer &amp; Context Provider</h3><p>Now that we have our testCaseReducer, testCaseState, and TestCaseContext, we want to provide it to the components that need it — the TestCase and ExportFileModal components.</p><p>If you take a look at a simplified version of the component tree for spearmint below, TestCase is a child component of the LeftPanel Container and ExportFileModal is a child component of the NavBar Container. Since App is the common parent component of LeftPanel and NavBar, we want to call useReducer in App.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b1b5V-NgedMYXTMrFMnA8A.png" /><figcaption>Spearmint component tree diagram</figcaption></figure><p>Here is the code for App.jsx. Again, irrelevant code was removed, and if you want to see the full code for App, you can visit the <a href="https://github.com/apark0720/spearmint/blob/master/src/App.jsx">GitHub</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cee454ffb11bb2553e3f7037a24f0ba9/href">https://medium.com/media/cee454ffb11bb2553e3f7037a24f0ba9/href</a></iframe><p>useReducer takes in two arguments, the first being the reducer and the second being the initial state. When invoked, it returns an array with the first value being the actual state, and the second value being a method to update the state that we assign to new variables using array destructuring.</p><p>Next, we wrap the components that we want to share the testCase state with the TestCaseContext.Provider. You can only provide one value to a Provider. In order to avoid creating separate Contexts for the testCase and dispatchToTestCase, we wrap the two in an array.</p><p>Note that this concept is similar to Redux and how it provides the store to your top-level component and all of its children. We just have to create separate providers for each reducer because we don’t have a global store ala Redux.</p><h3>Step 3: useContext</h3><p>After we have the Providers set up, we can access the value that we gave to the Provider through useContext. I like to think of useContext as something similar to Redux’s connect method where the component in question now has access to state and a dispatch method to update the state.</p><p>Below we are using useContext in the TestCase component. The unabridged code can be found at <a href="https://github.com/apark0720/spearmint/blob/master/src/containers/LeftPanel/TestCase/TestCase.jsx">this GitHub</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16e530d3b3d14d4890ca0e7dafec16d7/href">https://medium.com/media/16e530d3b3d14d4890ca0e7dafec16d7/href</a></iframe><p>In line 7, we useContext. You invoke it by passing in a context that you created, which in our case is the TestCaseContext. If you wrapped the component or one of its parent components in a Context.Provider, the return value will be equal to the value that you passed into the Provider. In our case, it is the array containing testCase and dispatchToTestCase. Here, we are destructuring testStatement and statements out from testCase because we do not need access to the other values in testCase.</p><p>Let’s look at how we are dispatching an action to the reducer in line 10. All we need to do is invoke dispatchToTestCase in order to dispatch an action object (the return value of an action creator) to the reducer.</p><h3>In Conclusion</h3><p>At this point, you might be wondering, “With Hooks and Context available to me, do I ever need to use Redux now?”</p><p>Well, here are some things that I missed from Redux:</p><ul><li>Time travel debugging! I’m back to console logging my reducer.</li><li>Not having a single source of truth, just multiple reducers.</li><li>Wrapping a component in a Context.Provider triggers a rerender of the wrapped component and all of its children when the provided changes (compared to Redux’s connect method automatically transform the component to a Pure.Component that prevents rerenders).</li></ul><p>It was nice removing a lot of code via Hooks and Context and reducing the application size by not having to install the redux and react-redux libraries. I actually think I prefer Redux for complex projects over Hooks and Context for the above reasons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ds1YVMQWssr1LeHe" /></figure><p>Feel free to ask any follow-up questions in the comment, and I’ll try to respond as soon as I can.</p><h3>Resources</h3><ul><li><a href="http://www.github.com/spearmintjs/spearmint">Spearmint.js on GitHub</a></li></ul><figure><a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_image"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PYxBP_WV7LI6zc-zdUkNqQ.png" /></a></figure><p>📝 Read this story later in <a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_read_later_text">Journal</a>.</p><p>👩‍💻 Wake up every Sunday morning to the week’s most noteworthy stories in Tech waiting in your inbox. <a href="https://usejournal.com/newsletter/noteworthy-in-tech/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_text">Read the Noteworthy in Tech newsletter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6ba1e00329d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>