<?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 Ye Min Ko on Medium]]></title>
        <description><![CDATA[Stories by Ye Min Ko on Medium]]></description>
        <link>https://medium.com/@marcodev?source=rss-15ef0d5d1990------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_cYKIk9WovOPnQY8zKFehg.jpeg</url>
            <title>Stories by Ye Min Ko on Medium</title>
            <link>https://medium.com/@marcodev?source=rss-15ef0d5d1990------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 08:40:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@marcodev/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[Using useEffectEvent() in React]]></title>
            <link>https://medium.com/learn-reactjs/using-useeffectevent-in-react-427756d6474a?source=rss-15ef0d5d1990------2</link>
            <guid isPermaLink="false">https://medium.com/p/427756d6474a</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ye Min Ko]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 11:57:27 GMT</pubDate>
            <atom:updated>2026-11-26T11:57:59.934Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kwkHKDe3Vm-RUro0" /><figcaption>Photo by <a href="https://unsplash.com/@nataliekinnear?utm_source=medium&amp;utm_medium=referral">Natalie Kinnear</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>useEffectEvent() is a React hook that allows you to create event handlers that can safely access the latest state and props without needing to include them in the dependency array of useEffect(). This can help prevent issues with stale closures and unnecessary re-renders.</p><h3>Before React 19.2</h3><p>useEffectEvent() was introduced in React 19.2. Before this version, developers often faced challenges when trying to access the latest state or props within event handlers defined inside useEffect().<br> One way to work around this was to use refs to store the latest state or props, but this approach could be cumbersome and error-prone. Learn more about this in <a href="https://medium.com/learn-reactjs/using-useref-to-reduce-useeffect-dependencies-7b1f7549091f">this article</a>.</p><h3>Example</h3><p>Let’s create a component called Chat.</p><blockquote><strong>Note:</strong> We will use same example from the article mentioned above to demonstrate how useEffectEvent() can simplify event handling in React.</blockquote><pre>import { useState } from &quot;react&quot;;<br>import Chatroom from &quot;./Chatroom&quot;;<br><br>export default function Chat() {<br>  const [roomId, setRoomId] = useState(&quot;1&quot;);<br>  const [nightTheme, setNightTheme] = useState(false);<br><br>  return (<br>    &lt;&gt;<br>      &lt;select value={roomId} onChange={(e) =&gt; setRoomId(e.target.value)}&gt;<br>        &lt;option value=&quot;1&quot;&gt;Room 1&lt;/option&gt;<br>        &lt;option value=&quot;2&quot;&gt;Room 2&lt;/option&gt;<br>        &lt;option value=&quot;3&quot;&gt;Room 3&lt;/option&gt;<br>      &lt;/select&gt;<br>      &lt;br /&gt;<br>      &lt;label&gt;Dark Theme: &lt;/label&gt;<br>      &lt;input<br>        type=&quot;checkbox&quot;<br>        checked={nightTheme}<br>        onChange={(e) =&gt; setNightTheme(e.target.checked)}<br>      /&gt;<br>      &lt;Chatroom roomId={roomId} nightTheme={nightTheme} /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>The component above allows the user to select a chat room and toggle a dark theme. The Chatroom component receives roomId and nightTheme as props.</p><h3>Chatroom Component</h3><p>Now let’s implement the Chatroom component, which logs a greeting message when the user changes chatrooms.</p><pre>import { useEffect } from &quot;react&quot;;<br><br>interface Props {<br>  roomId: string;<br>  nightTheme: boolean;<br>}<br><br>export default function Chatroom({ roomId, nightTheme }: Props) {<br>  useEffect(() =&gt; {<br>    if (nightTheme) {<br>      console.log(`Good night from room ${roomId}`);<br>    } else {<br>      console.log(`Good day from room ${roomId}.`);<br>    }<br>  }, [roomId, nightTheme]);<br><br>  return &lt;div&gt;You are in room {roomId}&lt;/div&gt;;<br>}</pre><p>In this implementation, the useEffect() hook logs a greeting message whenever roomId changes. The greeting message also depends on the user&#39;s selected theme, which is determined by the nightTheme prop. Therefore, both roomId and nightTheme must be included in the useEffect() dependency array.</p><h3>The problem</h3><p>We only want to log a greeting message when the user switches chatrooms. However, the greeting message is also logged whenever the user toggles the dark theme.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*HI_lnNzxOdxytGuMeuQZ0Q.gif" /><figcaption>Dependency issue with useEffect()</figcaption></figure><h3>Solution</h3><p>To solve this problem, we can use the useEffectEvent() hook to create an event handler that can safely access the latest state and props without needing to include them in the dependency array of useEffect(). Let&#39;s update the Chatroom component to use useEffectEvent():</p><pre>import { useEffect, useEffectEvent } from &quot;react&quot;;<br><br>interface Props {<br>  roomId: string;<br>  nightTheme: boolean;<br>}<br><br>export default function Chatroom({ roomId, nightTheme }: Props) {<br>  const isNightTheme = useEffectEvent(() =&gt; nightTheme);<br><br>  useEffect(() =&gt; {<br>    if (isNightTheme()) {<br>      console.log(`Good night from room ${roomId}`);<br>    } else {<br>      console.log(`Good day from room ${roomId}.`);<br>    }<br>  }, [roomId]);<br><br>  return &lt;div&gt;You are in room {roomId}&lt;/div&gt;;<br>}</pre><p>As you can see, we have replaced the nightTheme prop with the isNightTheme() function returned by useEffectEvent(). This allows us to access the latest value of nightTheme without including it in the dependency array of useEffect(). Now, the greeting message will only be logged when the user switches chatrooms, and not when they toggle the dark theme.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Tlmd0HPDWi2wzoAq3vVMfw.gif" /><figcaption>With useEffectEvent()</figcaption></figure><h3>Conclusion</h3><p>By using useEffectEvent(), we can create event handlers that safely access the latest state and props without needing to include them in the dependency array of useEffect(). This can help prevent issues with stale closures and unnecessary re-renders, making our React components more efficient and easier to maintain.</p><h3>More Resources</h3><p><a href="https://medium.com/learn-reactjs/using-useref-to-reduce-useeffect-dependencies-7b1f7549091f">Using useRef() to Reduce useEffect() Dependencies</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=427756d6474a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/learn-reactjs/using-useeffectevent-in-react-427756d6474a">Using useEffectEvent() in React</a> was originally published in <a href="https://medium.com/learn-reactjs">Learn React</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using useRef() to Reduce useEffect() Dependencies]]></title>
            <link>https://medium.com/learn-reactjs/using-useref-to-reduce-useeffect-dependencies-7b1f7549091f?source=rss-15ef0d5d1990------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b1f7549091f</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ye Min Ko]]></dc:creator>
            <pubDate>Wed, 11 Nov 2026 08:51:01 GMT</pubDate>
            <atom:updated>2026-11-26T11:59:12.740Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*98z8u8jDoy-FBTrp" /><figcaption>Photo by <a href="https://unsplash.com/@chloeforbesk?utm_source=medium&amp;utm_medium=referral">Chloë Forbes-Kindlen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>useEffect() is a powerful hook in React that allows you to perform side effects. However, it can sometimes lead to unnecessary re-renders or complex dependency arrays, especially when dealing with mutable values or references. In such cases, the useRef() hook can be a valuable tool to reduce the dependencies of useEffect() and improve performance.</p><h3>Example Component</h3><p>Let’s create a component called Chat.</p><pre>import { useState } from &quot;react&quot;;<br>import Chatroom from &quot;./Chatroom&quot;;<br><br>export default function Chat() {<br>  const [roomId, setRoomId] = useState(&quot;1&quot;);<br>  const [nightTheme, setNightTheme] = useState(false);<br><br>  return (<br>    &lt;&gt;<br>      &lt;select value={roomId} onChange={(e) =&gt; setRoomId(e.target.value)}&gt;<br>        &lt;option value=&quot;1&quot;&gt;Room 1&lt;/option&gt;<br>        &lt;option value=&quot;2&quot;&gt;Room 2&lt;/option&gt;<br>        &lt;option value=&quot;3&quot;&gt;Room 3&lt;/option&gt;<br>      &lt;/select&gt;<br>      &lt;br /&gt;<br>      &lt;label&gt;Dark Theme: &lt;/label&gt;<br>      &lt;input<br>        type=&quot;checkbox&quot;<br>        checked={nightTheme}<br>        onChange={(e) =&gt; setNightTheme(e.target.checked)}<br>      /&gt;<br>      &lt;Chatroom roomId={roomId} nightTheme={nightTheme} /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>The component above allows the user to select a chat room and toggle a dark theme. The Chatroom component receives roomId and nightTheme as props.</p><h3>Chatroom Component</h3><p>Now let’s implement the Chatroom component, which logs a greeting message when the user changes chatrooms.</p><pre>import { useEffect } from &quot;react&quot;;<br><br>interface Props {<br>  roomId: string;<br>  nightTheme: boolean;<br>}<br><br>export default function Chatroom({ roomId, nightTheme }: Props) {<br>  useEffect(() =&gt; {<br>    if (nightTheme) {<br>      console.log(`Good night from room ${roomId}`);<br>    } else {<br>      console.log(`Good day from room ${roomId}.`);<br>    }<br>  }, [roomId, nightTheme]);<br><br>  return &lt;div&gt;You are in room {roomId}&lt;/div&gt;;<br>}</pre><p>In this implementation, the useEffect() hook logs a greeting message whenever roomId changes. The greeting message also depends on the user&#39;s selected theme, which is determined by the nightTheme prop. Therefore, both roomId and nightTheme must be included in the useEffect() dependency array.</p><h3>The problem</h3><p>We only want to log a greeting message when the user switches chatrooms. However, the greeting message is also logged whenever the user toggles the dark theme.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*HI_lnNzxOdxytGuMeuQZ0Q.gif" /></figure><h3>Solution</h3><p>useRef() is a hook that lets you store a mutable value that persists between renders. But we can also use it to reduce the dependencies of useEffect(). Let&#39;s update the Chatroom component to use useRef().</p><pre>export default function Chatroom({ roomId, nightTheme }: Props) {<br>  const nightThemeRef = useRef(nightTheme);<br>  nightThemeRef.current = nightTheme;<br><br>  useEffect(() =&gt; {<br>    if (nightThemeRef.current) {<br>      console.log(`Good night from room ${roomId}`);<br>    } else {<br>      console.log(`Good day from room ${roomId}.`);<br>    }<br>  }, [roomId]);<br><br>  return &lt;div&gt;You are in room {roomId}&lt;/div&gt;;<br>}</pre><p>As you can see, we removed nightTheme from the dependency array of useEffect(). Instead, we use a ref to store the current value of nightTheme. This way, the greeting message is only logged when the user switches chatrooms, and not when they toggle the dark theme.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*gjU2iEOQiZpFg88XWxXv8A.gif" /></figure><blockquote><strong>Recommendation</strong>: Don’t always use useRef() just to reduce the dependencies of useEffect(). Instead, try to find a better way to remove unnecessary dependencies. For example, consider using an event handler instead of useEffect() when the logic is triggered by a user interaction. More on <a href="https://react.dev/learn/removing-effect-dependencies">React Docs</a>.</blockquote><h3>Conclusion</h3><p>In this article, we learned how to use useRef() to reduce the dependencies of useEffect(). By using a ref to store the current value of a prop or state, we can avoid unnecessary re-renders and improve performance. However, if you are using React version 19.2 or later, consider using useEffectEvent() instead, as it is a more suitable solution for this use case.</p><h3>More Resources</h3><ul><li><a href="https://medium.com/learn-reactjs/resetting-react-components-with-the-key-prop-68a570b5fdb6">Resetting React Components with the key Prop</a></li><li><a href="https://medium.com/learn-reactjs/using-useeffectevent-in-react-427756d6474a">Using useEffectEvent() in React</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b1f7549091f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/learn-reactjs/using-useref-to-reduce-useeffect-dependencies-7b1f7549091f">Using useRef() to Reduce useEffect() Dependencies</a> was originally published in <a href="https://medium.com/learn-reactjs">Learn React</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Resetting React Components with the key Prop]]></title>
            <link>https://medium.com/learn-reactjs/resetting-react-components-with-the-key-prop-68a570b5fdb6?source=rss-15ef0d5d1990------2</link>
            <guid isPermaLink="false">https://medium.com/p/68a570b5fdb6</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ye Min Ko]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 08:38:26 GMT</pubDate>
            <atom:updated>2026-11-11T08:51:54.622Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8hEQpTnnp4ZYeK-p" /><figcaption>Photo by <a href="https://unsplash.com/@leducduy?utm_source=medium&amp;utm_medium=referral">Duy Le Duc</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Components in React are designed to be reusable and maintain their state across renders. However, there are scenarios where you may want to reset a component’s state or force it to re-render from scratch. One effective way to achieve this is by using the key prop.</p><h3>The key Prop</h3><p>The key prop is a special attribute in React that helps identify which items have changed, are added, or are removed. When the key of a component changes, React treats it as a new component and will unmount the old one and mount the new one, effectively resetting its state.</p><h3>Example</h3><p>Let’s create a component called MessageForm that allows users to input a message.</p><pre>import { useState } from &quot;react&quot;;<br><br>interface Props {<br>  recipient: string;<br>}<br><br>export default function MessageForm({ recipient }: Props) {<br>  const [message, setMessage] = useState(&quot;&quot;);<br><br>  return (<br>    &lt;section&gt;<br>      &lt;h2&gt;Message to {recipient}&lt;/h2&gt;<br>      &lt;label&gt;Your message&lt;/label&gt;<br>      &lt;br /&gt;<br>      &lt;textarea<br>        value={message}<br>        onChange={(event) =&gt; setMessage(event.target.value)}<br>        rows={4}<br>      /&gt;<br>    &lt;/section&gt;<br>  );<br>}</pre><p>Nothing special here, just a simple form with a textarea. Now let’s create a parent component called Messenger that renders MessageForm and allows the user to change the recipient.</p><pre>import { useState } from &quot;react&quot;;<br>import MessageForm from &quot;./MessageForm&quot;;<br><br>const recipients = [&quot;Alice&quot;, &quot;Bob&quot;];<br><br>export default function Messenger() {<br>  const [recipient, setRecipient] = useState(recipients[0]);<br><br>  return (<br>    &lt;main&gt;<br>      {recipients.map((name) =&gt; (<br>        &lt;button key={name} onClick={() =&gt; setRecipient(name)}&gt;<br>          {name}<br>        &lt;/button&gt;<br>      ))}<br><br>      &lt;MessageForm recipient={recipient} /&gt;<br>    &lt;/main&gt;<br>  );<br>}</pre><p>In this example, we have a Messenger component that renders buttons for each recipient. When a button is clicked, it updates the recipient state, which is passed down to the MessageForm component.</p><p>The problem is that when you switch between recipients, the MessageForm component retains its state (the message typed in the textarea).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*4G7fmwNHWvDK5gwYg_BmKw.gif" /><figcaption>Without using key</figcaption></figure><p>You can see that the old message remains in the textarea even after switching recipients. This is because React reuses the same MessageForm component instance and does not reset its state.</p><h3>Using the key Prop to Reset State</h3><p>To reset the state of the MessageForm component when switching recipients, we can use the key prop. By assigning a unique key to the MessageForm based on the recipient, React will treat it as a new component whenever the recipient changes. Update the code in Messenger component as follows:</p><pre>&lt;MessageForm key={recipient} recipient={recipient} /&gt;</pre><p>We use the recipient as the key because it is unique for each recipient. Now, when you switch between recipients, the MessageForm component will reset its state and the textarea will be cleared.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*26rkrpxZZdEBfPy4JloE7A.gif" /><figcaption>With key</figcaption></figure><h3>Conclusion</h3><p>Using the key prop is a simple and effective way to reset a React component&#39;s state when necessary. By providing a unique key that changes based on certain conditions (like the recipient in our example), you can ensure that your components behave as expected and provide a better user experience.</p><h3>More Resources</h3><ul><li><a href="https://medium.com/learn-reactjs/using-context-in-react-3b7ad12a3f22">Using Context in React</a></li><li><a href="https://medium.com/learn-reactjs/using-useref-to-reduce-useeffect-dependencies-7b1f7549091f">Using useRef() to Reduce useEffect() Dependencies</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68a570b5fdb6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/learn-reactjs/resetting-react-components-with-the-key-prop-68a570b5fdb6">Resetting React Components with the key Prop</a> was originally published in <a href="https://medium.com/learn-reactjs">Learn React</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Context in React]]></title>
            <link>https://medium.com/learn-reactjs/using-context-in-react-3b7ad12a3f22?source=rss-15ef0d5d1990------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b7ad12a3f22</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ye Min Ko]]></dc:creator>
            <pubDate>Fri, 18 Sep 2026 09:49:05 GMT</pubDate>
            <atom:updated>2026-10-07T08:39:18.811Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dxll0S7ztLoyMvB_" /><figcaption>Photo by <a href="https://unsplash.com/@manuelventurini?utm_source=medium&amp;utm_medium=referral">Manuel Venturini</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>When we need to pass data from a parent component to a child component, we can use props. However, when we need to pass data from a grandparent component to a grandchild component, we have to pass the data all the way down through props, which can become cumbersome and difficult to manage. This is where React Context comes in handy.</p><h3>What is Context?</h3><p>Context is a way to share data between components without having to pass props down manually at every level. It allows us to create a global state that can be accessed by any component in the component tree.</p><blockquote>If you familiar with Redux, Zustand, or other state management libraries, you can think of Context as a simpler alternative for managing global state in React applications.</blockquote><h3>Creating a Context</h3><p>Let’s create a context called ProductContext that will hold an array of products.</p><blockquote>React context files are usually placed in a context folder in the src directory. You can create a new file called ProductContext.tsx in the context folder.</blockquote><pre>import { createContext, useState, useContext, type ReactNode } from &quot;react&quot;;<br><br>interface Product {<br>  id: number;<br>  name: string;<br>}<br><br>interface ContextValue {<br>  products: Product[];<br>  setProducts: (products: Product[]) =&gt; void;<br>}<br><br>// 1. Create the context<br>const ProductContext = createContext&lt;ContextValue | undefined&gt;(undefined);<br><br>// 2. Create the provider component<br>export function ProductContextProvider({ children }: { children: ReactNode }) {<br>  const [products, setProducts] = useState&lt;Product[]&gt;([]);<br><br>  const value = { products, setProducts };<br><br>  return &lt;ProductContext value={value}&gt;{children}&lt;/ProductContext&gt;;<br>}<br><br>// 3. Create a custom hook to use the context<br>export function useProductContext() {<br>  const context = useContext(ProductContext);<br>  if (!context) {<br>    throw new Error(<br>      &quot;useProductContext must be used within a ProductContextProvider&quot;,<br>    );<br>  }<br>  return context;<br>}</pre><p>There are a lot of things happening in the above code snippet, so let’s break it down step by step.</p><ul><li>Product and ContextValue are TypeScript interfaces that define the shape of the product data and the context value, respectively.</li><li>ProductContext is created using the createContext() function, which takes an initial value of undefined.</li><li>ProductContextProvider is a component that uses the useState() hook to manage the state of the products and provides the context value to its children. It takes a children prop, which is the content that will be wrapped by the provider.</li><li>useProductContext is a custom hook that allows us to access the context value from any component that is a descendant of the ProductContextProvider. It throws an error if it is used outside of the provider, ensuring that we are always using the context correctly.</li></ul><h3>Providing the Context</h3><p>Creating a context alone is not enough. We need to wrap our component tree with the ProductContextProvider so that all components can access the context value. Go to App component and wrap the component tree with the ProductContextProvider like this:</p><pre>export default function App() {<br>  return (<br>    &lt;ProductContextProvider&gt;<br>      &lt;Products /&gt;<br>      &lt;GetProducts /&gt;<br>    &lt;/ProductContextProvider&gt;<br>  );<br>}</pre><h3>Using the Context</h3><p>Now that we have provided the context, we can use it in any component that is a descendant of the ProductContextProvider. Let&#39;s see how we can use the context in the Products and GetProducts components.</p><h4>Products Component</h4><p>In the Products component, we will use the useProductContext hook to access the products from the context and display them. If there are no products available, we will display a message indicating that.</p><pre>export default function Products() {<br>  const { products } = useProductContext();<br>  return (<br>    &lt;&gt;<br>      {products.length === 0 &amp;&amp; &lt;div&gt;No products available&lt;/div&gt;}<br>      &lt;div&gt;<br>        {products.map((product) =&gt; (<br>          &lt;div key={product.id}&gt;{product.name}&lt;/div&gt;<br>        ))}<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><h4>GetProducts Component</h4><p>In the GetProducts component, we will use the useProductContext hook to access the setProducts function from the context. When the button is clicked, we will set the products in the context, which will trigger a re-render of the Products component and display the newly added products.</p><pre>export default function GetProducts() {<br>  const { setProducts } = useProductContext();<br><br>  function handleProducts() {<br>    setProducts([<br>      { id: 1, name: &quot;Product 1&quot; },<br>      { id: 2, name: &quot;Product 2&quot; },<br>      { id: 3, name: &quot;Product 3&quot; },<br>    ]);<br>  }<br><br>  return &lt;button onClick={handleProducts}&gt;Get Products&lt;/button&gt;;<br>}</pre><p>Notice that in App component, Products and GetProducts components does not pass any props to each other, but they can still communicate through the context. When the button in GetProducts is clicked, it updates the products in the context, and the Products component automatically re-renders to display the new products.</p><h3>Conclusion</h3><p>React Context is useful for sharing data between components without having to pass props down manually at every level. It allows us to create a global state that can be accessed by any component in the component tree. However, if you need to manage complex state that need frequent updates, you might want to consider using a state management library like Zustand or Redux instead of Context.</p><h3>More Resources</h3><ul><li><a href="https://medium.com/learn-reactjs/using-reducer-in-react-ab42ca5b3661">Using Reducer in React</a></li><li><a href="https://medium.com/learn-reactjs/resetting-react-components-with-the-key-prop-68a570b5fdb6">Resetting React Components with the key Prop</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b7ad12a3f22" width="1" height="1" alt=""><hr><p><a href="https://medium.com/learn-reactjs/using-context-in-react-3b7ad12a3f22">Using Context in React</a> was originally published in <a href="https://medium.com/learn-reactjs">Learn React</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is It Better to Live Alone or With Other People?]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://marcodev.medium.com/is-it-better-to-live-alone-or-with-other-people-9f83992b2469?source=rss-15ef0d5d1990------2"><img src="https://cdn-images-1.medium.com/max/2600/0*8IohCUwj04szv3oz" width="5873"></a></p><p class="medium-feed-snippet">Whether you live alone or with other people, each lifestyle has its own pros and cons.</p><p class="medium-feed-link"><a href="https://marcodev.medium.com/is-it-better-to-live-alone-or-with-other-people-9f83992b2469?source=rss-15ef0d5d1990------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://marcodev.medium.com/is-it-better-to-live-alone-or-with-other-people-9f83992b2469?source=rss-15ef0d5d1990------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f83992b2469</guid>
            <category><![CDATA[thoughts]]></category>
            <dc:creator><![CDATA[Ye Min Ko]]></dc:creator>
            <pubDate>Fri, 04 Sep 2026 05:26:01 GMT</pubDate>
            <atom:updated>2026-09-04T05:26:31.778Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Using Reducer in React]]></title>
            <link>https://medium.com/learn-reactjs/using-reducer-in-react-ab42ca5b3661?source=rss-15ef0d5d1990------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab42ca5b3661</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ye Min Ko]]></dc:creator>
            <pubDate>Mon, 31 Aug 2026 10:05:31 GMT</pubDate>
            <atom:updated>2026-09-18T09:50:34.764Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WhdADixVzthBAtGb" /><figcaption>Photo by <a href="https://unsplash.com/@shin1_de?utm_source=medium&amp;utm_medium=referral">shin1</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>A component can become more complex over time as more state variables and event handler functions are added. In such cases, we can use the useReducer() hook to manage state in a more organized and predictable way.</p><h3>Without using Reducer</h3><p>Let’s create a component called Server. The following code is written without using a reducer.</p><pre>import { useState } from &quot;react&quot;;<br><br>export default function Server() {<br>  const [status, setStatus] = useState&lt;string&gt;(&quot;Loading&quot;);<br><br>  function changeToOnline() {<br>    setStatus(&quot;Online&quot;);<br>  }<br><br>  function changeToOffline() {<br>    setStatus(&quot;Offline&quot;);<br>  }<br><br>  function changeToLoading() {<br>    setStatus(&quot;Loading&quot;);<br>  }<br><br>  return (<br>    &lt;&gt;<br>      &lt;h1&gt;Server Status: {status}&lt;/h1&gt;<br>      &lt;button onClick={changeToOnline}&gt;Online&lt;/button&gt;<br>      &lt;button onClick={changeToOffline}&gt;Offline&lt;/button&gt;<br>      &lt;button onClick={changeToLoading}&gt;Loading&lt;/button&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>Nothing new just using useState() to manage the state of the server status. We have three functions to change the status to &quot;Online&quot;, &quot;Offline&quot;, and &quot;Loading&quot;.</p><p>You can extract these functions into outside of the component by using reducer. Let&#39;s see how we can do that.</p><h3>Using Reducer</h3><p>Here is the code using useReducer() to manage the state of the server status.</p><pre>import { useReducer } from &quot;react&quot;;<br><br>type Action = {<br>  type: &quot;CHANGE_TO_ONLINE&quot; | &quot;CHANGE_TO_OFFLINE&quot; | &quot;CHANGE_TO_LOADING&quot;;<br>};<br><br>function statusReducer(state: string, action: Action): string {<br>  switch (action.type) {<br>    case &quot;CHANGE_TO_ONLINE&quot;:<br>      return &quot;Online&quot;;<br>    case &quot;CHANGE_TO_OFFLINE&quot;:<br>      return &quot;Offline&quot;;<br>    case &quot;CHANGE_TO_LOADING&quot;:<br>      return &quot;Loading&quot;;<br>    default:<br>      return state;<br>  }<br>}<br><br>const initialStatus = &quot;Loading&quot;;<br><br>export default function Server() {<br>  const [status, dispatch] = useReducer(statusReducer, initialStatus);<br><br>  return (<br>    &lt;&gt;<br>      &lt;h1&gt;Server Status: {status}&lt;/h1&gt;<br>      &lt;button onClick={() =&gt; dispatch({ type: &quot;CHANGE_TO_ONLINE&quot; })}&gt;<br>        Online<br>      &lt;/button&gt;<br>      &lt;button onClick={() =&gt; dispatch({ type: &quot;CHANGE_TO_OFFLINE&quot; })}&gt;<br>        Offline<br>      &lt;/button&gt;<br>      &lt;button onClick={() =&gt; dispatch({ type: &quot;CHANGE_TO_LOADING&quot; })}&gt;<br>        Loading<br>      &lt;/button&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>To create a reducer, we first define an action type that describes the possible actions that can be dispatched. In this case, we have three actions: “CHANGE_TO_ONLINE”, “CHANGE_TO_OFFLINE”, and “CHANGE_TO_LOADING”.</p><p>Then we define a reducer function called statusReducer that takes the current state and an action as arguments. The reducer function uses a switch statement to determine how to update the state based on the action type.</p><p>In Server component, we use the useReducer() hook to initialize the state and get the dispatch function. The dispatch function is used to send actions to the reducer, which updates the state accordingly.</p><p>It seems like a lot of code for a simple state management, but as the component grows and more states are added, using a reducer can help keep the code organized and maintainable.</p><h3>Carrying Payload</h3><p>You can also carry a payload with the action to make the reducer more flexible. For example, if we want to change the status to a custom value, we can modify the action type and the reducer function as follows:</p><pre>import { useReducer } from &quot;react&quot;;<br><br>type Action = {<br>  type: &quot;UPDATE_STATUS&quot;;<br>  payload: string;<br>};<br><br>function statusReducer(state: string, action: Action): string {<br>  switch (action.type) {<br>    case &quot;UPDATE_STATUS&quot;:<br>      return action.payload;<br>    default:<br>      return state;<br>  }<br>}<br><br>const initialStatus = &quot;Loading&quot;;<br><br>export default function Server() {<br>  const [status, dispatch] = useReducer(statusReducer, initialStatus);<br><br>  return (<br>    &lt;&gt;<br>      &lt;h1&gt;Server Status: {status}&lt;/h1&gt;<br>      &lt;button<br>        onClick={() =&gt; dispatch({ type: &quot;UPDATE_STATUS&quot;, payload: &quot;Online&quot; })}<br>      &gt;<br>        Online<br>      &lt;/button&gt;<br>      &lt;button<br>        onClick={() =&gt; dispatch({ type: &quot;UPDATE_STATUS&quot;, payload: &quot;Offline&quot; })}<br>      &gt;<br>        Offline<br>      &lt;/button&gt;<br>      &lt;button<br>        onClick={() =&gt; dispatch({ type: &quot;UPDATE_STATUS&quot;, payload: &quot;Loading&quot; })}<br>      &gt;<br>        Loading<br>      &lt;/button&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>As you can see, we have modified the action type to “UPDATE_STATUS” and added a payload property to carry the new status value. The reducer function now updates the state based on the payload value.</p><h3>Conclusion</h3><p>Reducer is a powerful tool for managing state in React applications, especially when dealing with complex state logic or multiple state variables. By using useReducer(), we can keep our code organized, maintainable, and more predictable.</p><h3>More Resources</h3><ul><li><a href="https://medium.com/learn-reactjs/using-memo-in-react-to-optimize-performance-fd404a322d8d">Using memo in React to Optimize Performance</a></li><li><a href="https://medium.com/learn-reactjs/using-context-in-react-3b7ad12a3f22">Using Context in React</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab42ca5b3661" width="1" height="1" alt=""><hr><p><a href="https://medium.com/learn-reactjs/using-reducer-in-react-ab42ca5b3661">Using Reducer in React</a> was originally published in <a href="https://medium.com/learn-reactjs">Learn React</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using memo in React to Optimize Performance]]></title>
            <link>https://medium.com/learn-reactjs/using-memo-in-react-to-optimize-performance-fd404a322d8d?source=rss-15ef0d5d1990------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd404a322d8d</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ye Min Ko]]></dc:creator>
            <pubDate>Fri, 14 Aug 2026 10:38:55 GMT</pubDate>
            <atom:updated>2026-08-31T10:06:25.935Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_dlnRjJ0NjijLyNu" /><figcaption>Photo by <a href="https://unsplash.com/@saurinaf?utm_source=medium&amp;utm_medium=referral">Flor Saurina</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>When parent component re-renders, all of its child components will also re-render. This can lead to performance issues, especially if the child components are complex or if they receive props that haven’t changed. We can optimize performance in React by using React.memo to prevent unnecessary re-renders of child components.</p><h3>Understanding the Problem</h3><p>Let’s create a component called Parent.</p><pre>import { useState } from &quot;react&quot;;<br>import Child from &quot;./Child&quot;;<br><br>export default function Parent() {<br>  const [count, setCount] = useState(0);<br>  const [status, setStatus] = useState(&quot;Active&quot;);<br><br>  return (<br>    &lt;&gt;<br>      &lt;h1&gt;Count: {count}&lt;/h1&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment&lt;/button&gt;<br>      &lt;button<br>        onClick={() =&gt; setStatus(status === &quot;Active&quot; ? &quot;Inactive&quot; : &quot;Active&quot;)}<br>      &gt;<br>        Toggle Status<br>      &lt;/button&gt;<br>      &lt;Child status={status} /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>Nothing special here, let’s create a child component called Child.</p><pre>interface Props {<br>  status: string;<br>}<br><br>export default function Child({ status }: Props) {<br>  console.log(&quot;Child rendered&quot;);<br><br>  return &lt;h1&gt;Status: {status}&lt;/h1&gt;;<br>}</pre><p>When you click the “Increment” button in the Parent component, it will re-render, causing the Child component to also re-render even though its props (status) haven&#39;t changed. This is unnecessary and can lead to performance issues in larger applications. (Open the browser console to see the log messages.)</p><h3>Using memo</h3><p>To prevent the Child component from re-rendering unnecessarily, we can wrap it with memo. This will memoize the component and only re-render it if its props change.</p><pre>import { memo } from &quot;react&quot;;<br><br>interface Props {<br>  status: string;<br>}<br><br>export default memo(function Child({ status }: Props) {<br>  console.log(&quot;Child rendered&quot;);<br><br>  return &lt;h1&gt;Status: {status}&lt;/h1&gt;;<br>});</pre><p>Now, when you click the “Increment” button in the Parent component, the Child component will not re-render because its props haven&#39;t changed. But if you click the &quot;Toggle Status&quot; button, the Child component will re-render because its props have changed. (If it didn&#39;t work, refresh the page and try again.)</p><h3>Using together with useCallback</h3><p>memo only works for props that are primitive values (like strings, numbers, and booleans). If you pass a function as a prop to the child component, it will always be a new function reference on every render, causing the child component to re-render even if the function&#39;s logic hasn&#39;t changed. To solve this, we can use useCallback to memoize the function.</p><p>Let’s modify the Parent component to pass a function as a prop to the Child component.</p><pre>import { useState } from &quot;react&quot;;<br>import Child from &quot;./Child&quot;;<br><br>export default function Parent() {<br>  const [count, setCount] = useState(0);<br><br>  function print(text: string) {<br>    console.log(text);<br>  }<br><br>  return (<br>    &lt;&gt;<br>      &lt;h1&gt;Count: {count}&lt;/h1&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment&lt;/button&gt;<br>      &lt;Child print={print} /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>And modify the Child component to accept the print function as a prop.</p><pre>import { memo } from &quot;react&quot;;<br><br>interface Props {<br>  print: (text: string) =&gt; void;<br>}<br><br>export default memo(function Child({ print }: Props) {<br>  console.log(&quot;Child rendered&quot;);<br><br>  return &lt;button onClick={() =&gt; print(&quot;Hello!&quot;)}&gt;Print Hello!&lt;/button&gt;;<br>});</pre><p>As you can see, we wrap the Child component with memo, but it will still re-render every time when you click the &quot;Increment&quot; button in the Parent component because the print function is a new reference on every render. To fix this, we can use useCallback to memoize the print function.</p><pre>import { useCallback, useState } from &quot;react&quot;;<br>import Child from &quot;./Child&quot;;<br><br>export default function Parent() {<br>  const [count, setCount] = useState(0);<br><br>  const print = useCallback((text: string) =&gt; {<br>    console.log(text);<br>  }, []);<br><br>  return (<br>    &lt;&gt;<br>      &lt;h1&gt;Count: {count}&lt;/h1&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment&lt;/button&gt;<br>      &lt;Child print={print} /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>Now, when you click the “Increment” button in the Parent component, the Child component will not re-render because the print function is memoized and its reference doesn&#39;t change on every render.</p><h3>React Compiler</h3><p>React compiler can automatically optimize the rendering of components without using memo or useCallback. To learn more about this, you can read the article <a href="https://react.dev/learn/react-compiler/introduction">React Compiler</a>.</p><h3>Conclusion</h3><p>Using memo and useCallback together can help optimize performance in React applications by preventing unnecessary re-renders of child components. However, it&#39;s important to use these tools judiciously, as they can add complexity to your code. Always profile your application and identify performance bottlenecks before applying these optimizations.</p><h3>More Resources</h3><ul><li><a href="https://medium.com/learn-reactjs/usecallback-in-react-3e3afe63e698">useCallback() in React</a></li><li><a href="https://medium.com/learn-reactjs/using-reducer-in-react-ab42ca5b3661">Using Reducer in React</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd404a322d8d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/learn-reactjs/using-memo-in-react-to-optimize-performance-fd404a322d8d">Using memo in React to Optimize Performance</a> was originally published in <a href="https://medium.com/learn-reactjs">Learn React</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[useCallback() in React]]></title>
            <link>https://medium.com/learn-reactjs/usecallback-in-react-3e3afe63e698?source=rss-15ef0d5d1990------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e3afe63e698</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ye Min Ko]]></dc:creator>
            <pubDate>Wed, 05 Aug 2026 09:44:03 GMT</pubDate>
            <atom:updated>2026-08-14T10:43:20.811Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*04G0Sxl4-dQZ2fIj" /><figcaption>Photo by <a href="https://unsplash.com/@kiyoshi_jpg?utm_source=medium&amp;utm_medium=referral">Andres Medina</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>When you pass a function as a dependency to useEffect(), you might encounter issues if the function is recreated on every render. This can lead to unnecessary re-renders or even infinite loops. To avoid this, you can use useCallback() to memoize the function, ensuring that it only changes when its dependencies change.</p><h3>Understanding the Problem</h3><p>To understand the problem, consider the following example:</p><pre>import { useEffect, useState } from &quot;react&quot;;<br><br>export function InfinityLoop() {<br>  const [count, setCount] = useState(0);<br><br>  function prettyPrint() {<br>    console.log(&quot;Pretty Print&quot;);<br>  }<br><br>  useEffect(() =&gt; {<br>    prettyPrint();<br>    setCount((prevCount) =&gt; prevCount + 1);<br>  }, [prettyPrint]);<br><br>  return &lt;h1&gt;Current Count : {count}&lt;/h1&gt;;<br>}</pre><p>In this example, useEffect() calls both prettyPrint() and setCount(). Since prettyPrint() is used inside the effect, it is included in the dependency array. However, when you run this code, the count state increases indefinitely, resulting in an infinite loop.</p><p>This happens because calling setCount() updates the state, which causes the component to re-render. On every re-render, React creates a new prettyPrint() function. Because the function reference has changed, React considers the dependency to have changed, so it runs the effect again. The effect then calls setCount(), triggering another re-render, and the cycle repeats.</p><blockquote><strong>Note:</strong> Every time a component re-renders, React recreates all functions declared inside the component. This means a function such as prettyPrint() will have a new reference on every render. If you include such a function in a useEffect() dependency array, the effect will run after every render because the function reference is always different.</blockquote><h3>Solution</h3><p>To solve this problem, you can use the useCallback() hook to memoize the function. This ensures that the function reference remains the same across renders unless its dependencies change. Here&#39;s how you can modify the previous example:</p><pre>import { useEffect, useState, useCallback } from &quot;react&quot;;<br><br>export function InfinityLoop() {<br> const [count, setCount] = useState(0);<br><br> const prettyPrint = useCallback(() =&gt; {<br>  console.log(&quot;Pretty Print&quot;);<br> }, []); // No dependencies, so the function reference will remain the same<br><br> useEffect(() =&gt; {<br>  prettyPrint();<br>  setCount((prevCount) =&gt; prevCount + 1);<br> }, [prettyPrint]);<br><br> return &lt;h1&gt;Current Count : {count}&lt;/h1&gt;;<br>}</pre><p>useCallback() takes two arguments: the function you want to memoize and an array of dependencies. In this case, the dependency array is empty, meaning that prettyPrint() will not change unless the component is unmounted and remounted.</p><h3>When to Use useCallback()</h3><p>You should use useCallback() when you want to prevent a function from being recreated on every render, especially when that function is used as a dependency in useEffect(). This can help optimize performance and avoid unnecessary re-renders.</p><h3>Conclusion</h3><p>In summary, useCallback() is a useful React hook that memoizes a function so it isn&#39;t recreated on every render. You&#39;ll often use it when passing a function as a dependency to useEffect(), helping you avoid unnecessary effect executions. It also works well with React.memo() to reduce unnecessary re-renders of child components that receive callback functions as props. We&#39;ll explore this optimization in <a href="https://medium.com/learn-reactjs/using-memo-in-react-to-optimize-performance-fd404a322d8d">this article</a>.</p><h3>More Resources</h3><ul><li><a href="https://medium.com/learn-reactjs/using-useeffect-in-react-43525e00b1d7">Using useEffect() in React</a></li><li><a href="https://medium.com/learn-reactjs/using-memo-in-react-to-optimize-performance-fd404a322d8d">Using memo in React to Optimize Performance</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e3afe63e698" width="1" height="1" alt=""><hr><p><a href="https://medium.com/learn-reactjs/usecallback-in-react-3e3afe63e698">useCallback() in React</a> was originally published in <a href="https://medium.com/learn-reactjs">Learn React</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using useEffect() in React]]></title>
            <link>https://medium.com/learn-reactjs/using-useeffect-in-react-43525e00b1d7?source=rss-15ef0d5d1990------2</link>
            <guid isPermaLink="false">https://medium.com/p/43525e00b1d7</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ye Min Ko]]></dc:creator>
            <pubDate>Tue, 28 Jul 2026 09:35:03 GMT</pubDate>
            <atom:updated>2026-08-05T09:45:26.153Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7xR5cf1AYXAAZfyR" /><figcaption>Photo by <a href="https://unsplash.com/@steve_j?utm_source=medium&amp;utm_medium=referral">Steve A Johnson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In React, useEffect() is a hook that allows you to perform side effects in components. Side effects can include data fetching, subscriptions, or manually changing the DOM. The useEffect() hook is called after the component renders and can be used to synchronize your component with external systems.</p><h3>Running an Effect After Every Render</h3><p>To run an effect after every render, simply call useEffect() without a dependency array. This will cause the effect to run after every render of the component.</p><p>Without dependency array useEffect() will run on:</p><ul><li>Initial component mount.</li><li>Every re-render (state change, props change, etc.)</li></ul><pre>import { useEffect, useState } from &quot;react&quot;;<br><br>export default function RunEveryRender() {<br>  const [count, setCount] = useState(0);<br><br>  useEffect(() =&gt; {<br>    console.log(&quot;useEffect() is called!&quot;);<br>  });<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;useEffect() runs on every render.&lt;/h1&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Count: {count}&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>In this example, the useEffect() hook is called after every render of the component. Clicking the button will update the state and trigger a re-render, causing the effect to run again. Open your browser console to see the log messages.</p><blockquote>Note: In development mode, React will intentionally double-invoke certain lifecycle methods (including useEffect) to help identify side effects. This means that the effect will run twice on the initial render in development mode, but only once in production mode.</blockquote><h3>Running an Effect Only Once</h3><p>When you pass an empty dependency array [] to useEffect(), it will run only once after the initial render of the component.</p><p>With empty dependency array useEffect() will run on:</p><ul><li>Initial component mount.</li></ul><pre>import { useEffect, useState } from &quot;react&quot;;<br><br>export default function RunOnlyOnce() {<br>  const [count, setCount] = useState(0);<br><br>  useEffect(() =&gt; {<br>    console.log(&quot;useEffect() is called!&quot;);<br>  }, []);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;useEffect() runs only once.&lt;/h1&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Count: {count}&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>With this setup, the useEffect() hook runs only once after the component mounts. Clicking the button to update the state does not trigger the effect again because the dependency array is empty. In development mode, you will see the log message twice because of React&#39;s Strict Mode. However, in production mode, it runs only once.</p><h3>Running an Effect When Dependencies Change</h3><p>When you pass a dependency array with specific values to useEffect(), the effect will run after the initial render and whenever any of the dependencies change.</p><p>With dependency array useEffect() will run on:</p><ul><li>Initial component mount.</li><li>Whenever any value in the dependency array changes.</li></ul><pre>import { useState, useEffect } from &quot;react&quot;;<br><br>export default function RunWhenDependencyChange() {<br>  const [count, setCount] = useState(0);<br>  const [name, setName] = useState(&quot;&quot;);<br><br>  useEffect(() =&gt; {<br>    console.log(&quot;useEffect() is called!&quot;);<br>  }, [count]);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;useEffect() runs when the dependency changes.&lt;/h1&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Count: {count}&lt;/button&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        value={name}<br>        onChange={(e) =&gt; setName(e.target.value)}<br>        placeholder=&quot;Enter your name&quot;<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>In this example, the useEffect() hook runs after the initial render and whenever the count state changes. It does not run when the name state changes because name is not included in the dependency array.</p><p>If you’d like to experiment, add name to the dependency array. You&#39;ll see that the effect runs whenever either count or name changes.</p><h3>Cleaning Up an Effect</h3><p>When using useEffect(), you may need to clean up resources to prevent memory leaks or unwanted behavior. You can return a clean-up function from the effect, which will run when the component unmounts or before the effect runs again.</p><p>Clean-up function will run on:</p><ul><li>Component unmount.</li><li><strong>Before</strong> the effect runs again (if dependencies change).</li></ul><pre>import { useState, useEffect } from &quot;react&quot;;<br><br>export default function CleanUpEffect() {<br>  const [count, setCount] = useState(0);<br><br>  useEffect(() =&gt; {<br>    console.log(&quot;useEffect() is called!&quot;);<br><br>    return () =&gt; {<br>      console.log(&quot;Clean up function is called!&quot;);<br>    };<br>  }, [count]);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;useEffect() with clean up function.&lt;/h1&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Count: {count}&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>In this example, the clean-up function is called before the effect runs again when the count state changes. It is also called when the component unmounts.</p><h3>Infinite Loop with useEffect()</h3><p>useEffect() runs whenever one of the values in its dependency array changes. If the effect updates one of those dependencies, it will trigger another render, causing the effect to run again. This creates an infinite loop.</p><pre>import { useState, useEffect } from &quot;react&quot;;<br><br>export default function InfiniteLoopExample() {<br>  const [count, setCount] = useState(0);<br><br>  useEffect(() =&gt; {<br>    console.log(&quot;useEffect() is called!&quot;);<br><br>    // This causes an infinite loop<br>    setCount(count + 1);<br>  }, [count]);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Infinite Loop Example&lt;/h1&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>In this example, useEffect() depends on count. Each time the effect runs, it increments count by calling setCount(). Updating count causes the component to re-render, and because count has changed, the effect runs again. This cycle continues indefinitely, resulting in an infinite loop.</p><p>To avoid this problem, do not update a state variable inside an effect if that same state variable is included in the dependency array. If you need to update the state, consider restructuring your logic so the effect depends on different values or performs the update only when necessary.</p><h3>Linting</h3><p>To help catch potential issues with useEffect(), you can use the React Hooks ESLint plugin. This plugin provides linting rules that enforce best practices for using hooks, including useEffect(). Learn more about it here: <a href="https://react.dev/learn/editor-setup#linting"><strong>Linting</strong></a>.</p><h3>Best Practice</h3><p>Avoid using useEffect() unless it&#39;s truly necessary. Whenever possible, write your component logic without relying on effects, as this often results in simpler, more predictable, and easier-to-maintain code. Before adding a useEffect(), consider whether the logic can be handled during rendering or in an event handler instead. To learn more, read the official React guide: <a href="https://react.dev/learn/you-might-not-need-an-effect"><strong>You Might Not Need an Effect</strong></a>.</p><h3>Conclusion</h3><p>useEffect() is a powerful hook in React that allows you to manage side effects in function components. By understanding how to use it correctly, including its dependency array and clean-up functions, you can avoid common pitfalls like infinite loops and ensure your components behave as expected.</p><h3>More Resources</h3><ul><li><a href="https://medium.com/learn-reactjs/using-portal-in-react-7169de322c11">Using Portal in React</a></li><li><a href="https://medium.com/learn-reactjs/usecallback-in-react-3e3afe63e698">useCallback() in React</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43525e00b1d7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/learn-reactjs/using-useeffect-in-react-43525e00b1d7">Using useEffect() in React</a> was originally published in <a href="https://medium.com/learn-reactjs">Learn React</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Portal in React]]></title>
            <link>https://medium.com/learn-reactjs/using-portal-in-react-7169de322c11?source=rss-15ef0d5d1990------2</link>
            <guid isPermaLink="false">https://medium.com/p/7169de322c11</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ye Min Ko]]></dc:creator>
            <pubDate>Tue, 23 Jun 2026 08:55:02 GMT</pubDate>
            <atom:updated>2026-06-23T08:56:29.641Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bL8ieBtvVoy9QmZV" /><figcaption>Photo by <a href="https://unsplash.com/@thanhharry?utm_source=medium&amp;utm_medium=referral">Harry Tran</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Sometimes, you need to render a component outside of its normal hierarchy to avoid stacking and overflow issues or to ensure it behaves correctly. A common example is a modal, which should appear above all other content. In these situations, you can use a React Portal. React Portals allow you to render a component into a different location in the DOM while still keeping it part of the same React component tree.</p><h3>Without using Portal</h3><p>Let’s create a simple component called ComplexHeader and write the following code:</p><pre>export default function ComplexHeader() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Welcome&lt;/h1&gt;<br>      &lt;ul&gt;<br>        &lt;li&gt;<br>          &lt;h3&gt;First Menu&lt;/h3&gt;<br>        &lt;/li&gt;<br>        &lt;li&gt;<br>          &lt;h3&gt;Second Menu&lt;/h3&gt;<br>        &lt;/li&gt;<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>As you can see the component only include some headers and a list. Call the component in App.tsx and run it to see the output. When you open the developer tools, you will see the DOM structure is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iTU0D61vl_cG1FVo1BBsUg.png" /><figcaption>Without using Portal</figcaption></figure><p>The ComplexHeader component is rendered inside the root div, which is the default behavior in React. Let&#39;s say we want to render the &lt;h3&gt;Second Menu&lt;/h3&gt; outside of the root div, for example, in a different div with an id of my-portal. To achieve this, we can use React Portals.</p><h3>Using Portal</h3><p>To use a portal, we first need to create a new div in our HTML file with an id of my-portal. Open the public/index.html file and add the following code:</p><pre>&lt;body&gt;<br>    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>    &lt;!-- Add a new div for the portal --&gt;<br>    &lt;div id=&quot;my-portal&quot;&gt;&lt;/div&gt;<br>    &lt;script type=&quot;module&quot; src=&quot;/src/main.tsx&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;</pre><p>Next, create a component called Portal and write the following code:</p><pre>import type { ReactNode } from &quot;react&quot;;<br>import { createPortal } from &quot;react-dom&quot;;<br><br>interface Props {<br>  children: ReactNode;<br>}<br><br>export default function Protal({ children }: Props) {<br>  const portalId = document.getElementById(&quot;my-portal&quot;);<br><br>  return createPortal(children, portalId!);<br>}</pre><p>The Portal component takes a children prop, which is the content we want to render in the portal. We use the createPortal function from React to render the children into the div with the id of my-portal.</p><p>Now, let’s modify the ComplexHeader component to use the Portal component. Update the code as follows:</p><pre>import Protal from &quot;./Portal&quot;;<br><br>export default function ComplexHeader() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Welcome&lt;/h1&gt;<br>      &lt;ul&gt;<br>        &lt;li&gt;<br>          &lt;h3&gt;First Menu&lt;/h3&gt;<br>        &lt;/li&gt;<br>        &lt;li&gt;<br>          &lt;Protal&gt;<br>            &lt;h3&gt;Second Menu&lt;/h3&gt;<br>          &lt;/Protal&gt;<br>        &lt;/li&gt;<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Now, when you run the application and open the developer tools, you will see that the &lt;h3&gt;Second Menu&lt;/h3&gt; is rendered inside the my-portal div instead of the root div. The DOM structure will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qD4HzDM1Os59GXbmpUjNow.png" /><figcaption>With Portal</figcaption></figure><h3>Conclusion</h3><p>By using React Portals, we can render components outside of their normal hierarchy while still keeping them part of the same React component tree. This is particularly useful for modals, tooltips, and other UI elements that need to appear above other content.</p><h3>More Resources</h3><p><a href="https://medium.com/learn-reactjs/using-useimperativehandle-to-expose-child-methods-to-parent-components-in-react-f1e0ffe1ab1d">Using useImperativeHandle() to Expose Child Methods to Parent Components in React</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7169de322c11" width="1" height="1" alt=""><hr><p><a href="https://medium.com/learn-reactjs/using-portal-in-react-7169de322c11">Using Portal in React</a> was originally published in <a href="https://medium.com/learn-reactjs">Learn React</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>