<?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 xctk on Medium]]></title>
        <description><![CDATA[Stories by xctk on Medium]]></description>
        <link>https://medium.com/@lovexctk?source=rss-c5b4ba7fd4b2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*lVGLi2HtJoX8jJH9_SSMlA.jpeg</url>
            <title>Stories by xctk on Medium</title>
            <link>https://medium.com/@lovexctk?source=rss-c5b4ba7fd4b2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 17:42:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lovexctk/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[How to Escape the Closure Trap in React]]></title>
            <link>https://medium.com/@lovexctk/how-to-escape-the-closure-trap-in-react-d243c67f8a8e?source=rss-c5b4ba7fd4b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d243c67f8a8e</guid>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[xctk]]></dc:creator>
            <pubDate>Tue, 12 Dec 2023 10:23:54 GMT</pubDate>
            <atom:updated>2023-12-12T10:23:54.809Z</atom:updated>
            <content:encoded><![CDATA[<p>As is well known, closures in JavaScript are certainly one of the most daunting features of the language, even the all-knowing ChatGPT agrees. Additionally, they might also be one of the most elusive language features. We often use them when writing React code, but most of the time we don’t even realize it. However, we can’t do without them: if we want to write complex and high-performance React applications, we must understand closures. So, today let’s learn about the following points:</p><ol><li>What are closures, how do they arise, and why do we need them.</li><li>What are stale closures, and why do they occur.</li><li>What are the common scenarios in React that lead to stale closures, and how to deal with them. Warning: If you have never encountered closures in React, this article might blow your mind. When reading, make sure to carry enough chocolate to stimulate your brain cells.</li></ol><h3>One Common Problem</h3><p>For instance, consider this scenario: you are implementing a form with several input fields. One of the fields comes from an external component library. You can’t access its internal structure, so you can’t fix its performance issues. But you do need to use it in the form, so you decide to wrap it with React.memo to minimize its re-rendering as much as possible when the state in the form changes. Something like this:</p><pre>const HeavyComponentMemo = React.memo(HeavyComponent);<br><br>const Form = () =&gt; {<br>  const [value, setValue] = useState();<br><br>  return (<br>    &lt;&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        value={value}<br>        onChange={(e) =&gt; setValue(e.target.value)}<br>      /&gt;<br>      &lt;HeavyComponentMemo /&gt;<br>    &lt;/&gt;<br>  );<br>};</pre><p>This Heavy component only accepts a single string prop (such as title) and an onClick callback. When you click the &quot;Complete&quot; button inside the component, this callback is triggered. If you want to submit form data upon clicking, it&#39;s also straightforward: just pass the title and onClick props to it.</p><pre>const HeavyComponentMemo = React.memo(HeavyComponent);<br><br>const Form = () =&gt; {<br>  const [value, setValue] = useState();<br><br>  const onClick = () =&gt; {<br>    // submit our form data here<br>    console.log(value);<br>  };<br><br>  return (<br>    &lt;&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        value={value}<br>        onChange={(e) =&gt; setValue(e.target.value)}<br>      /&gt;<br>      &lt;HeavyComponentMemo<br>        title=&quot;Welcome to the form&quot;<br>        onClick={onClick}<br>      /&gt;<br>    &lt;/&gt;<br>  );<br>};</pre><p>Now, you will face a new problem. We know that every prop on a component wrapped with React.memo must be a primitive value, or remain unchanged during re-renders. Otherwise, memoization is ineffective. So, technically, we need to wrap onClick with useCallback:</p><pre>const onClick = useCallback(() =&gt; {<br>  // submit data here<br>}, []);</pre><p>But we also know that the useCallback hook should declare all dependencies in its dependency array. Therefore, if we want to submit form data within it, we must declare that data as a dependency:</p><pre>const onClick = useCallback(() =&gt; {<br>  // submit data here<br>  console.log(value);<br><br>  // adding value to the dependency<br>}, [value]);</pre><p>The challenge now is that even though our onClick is memoized, it still changes every time there&#39;s new input in the form. Therefore, our performance optimization is futile.</p><p>Let’s look for other solutions. React.memo has something called a comparison function, which allows us to have more fine-grained control over the comparison of props within React.memo. Normally, React compares the props itself. If we provide this function, it will depend on the result it returns. If the result is true, then React will know the props are the same, and the component should not be re-rendered, which sounds exactly like what we need. We only need to update one prop, which is our title, so it won’t be too complicated:</p><pre>const HeavyComponentMemo = React.memo(<br>  HeavyComponent,<br>  (before, after) =&gt; {<br>    return before.title === after.title;<br>  },<br>);</pre><p>So, the complete code looks like this:</p><pre>const HeavyComponentMemo = React.memo(<br>  HeavyComponent,<br>  (before, after) =&gt; {<br>    return before.title === after.title;<br>  },<br>);<br><br>const Form = () =&gt; {<br>  const [value, setValue] = useState();<br><br>  const onClick = () =&gt; {<br>    // submit our form data here<br>    console.log(value);<br>  };<br><br>  return (<br>    &lt;&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        value={value}<br>        onChange={(e) =&gt; setValue(e.target.value)}<br>      /&gt;<br>      &lt;HeavyComponentMemo<br>        title=&quot;Welcome to the form&quot;<br>        onClick={onClick}<br>      /&gt;<br>    &lt;/&gt;<br>  );<br>};</pre><p>It works. When we type in the input box, the Heavy component does not re-render, and the performance is not affected.</p><p>But now we encounter a new problem: if we type something in the input box and then press the button, the value printed in onClick is undefined. But it can&#39;t be undefined; if I add a console.log outside of onClick, it prints correctly.</p><pre>// those one logs it correctly<br>console.log(value);<br><br>const onClick = () =&gt; {<br>  // this is always undefined<br>  console.log(value);<br>};</pre><p>What’s going on here?</p><p>This is the so-called “stale closure” issue. To solve this problem, we first need to understand one of the most daunting topics in JavaScript: closures and how they work.</p><h3>JavaScript, Scope, and Closures</h3><p>Let’s start with functions and variables. What happens when we declare a regular function or an arrow function in JavaScript?</p><pre>function something() {<br>  //<br>}<br>const something = () =&gt; {};</pre><p>Let’s start with functions and variables. What happens when we declare a regular function or an arrow function in JavaScript?</p><pre>const something = () =&gt; {<br>  const value = &#39;text&#39;;<br>};<br><br>console.log(value); // not going to work, &quot;value&quot; is local to &quot;something&quot; function</pre><p>By doing this, we create a local scope: an area in the code where variables declared are invisible from the outside.</p><pre>const something = () =&gt; {<br>  const inside = () =&gt; {<br>    const value = &#39;text&#39;;<br>  };<br><br>  console.log(value); // not going to work, &quot;value&quot; is local to &quot;inside&quot; function<br>};</pre><p>However, it’s different in the opposite direction. The innermost function can access all variables declared outside of it.</p><pre>const something = () =&gt; {<br>  const value = &#39;text&#39;;<br><br>  const inside = () =&gt; {<br>    // perfectly fine, value is available here<br>    console.log(value);<br>  };<br>};</pre><p>This is achieved by creating what’s called a “closure.” The inner function “closes over” all data from the outside, essentially taking a snapshot of all “external” data, which is then frozen and stored separately in memory. What if, instead of creating this value within the something function, we pass it as an argument and return the inner function?</p><pre>const something = (value) =&gt; {<br>  const inside = () =&gt; {<br>    // perfectly fine, value is available here<br>    console.log(value);<br>  };<br><br>  return inside;<br>};</pre><p>We would get this behavior:</p><pre>const first = something(&#39;first&#39;);<br>const second = something(&#39;second&#39;);<br><br>first(); // logs &quot;first&quot;<br>second(); // logs &quot;second&quot;</pre><p>When we call the something function and pass in the value first, we assign the result to a variable. The result is a reference to the function declared inside, forming a closure. From now on, as long as the first variable that holds this reference exists, the value first that we passed to it will be frozen, and the inner function will be able to access it.</p><p>The same happens with the second call: we pass a different value, form a closure, and the returned function will always have access to that variable.</p><p>This is true for any variable locally declared within the something function:</p><pre>const something = (value) =&gt; {<br>  const r = Math.random();<br><br>  const inside = () =&gt; {<br>    // ...<br>  };<br><br>  return inside;<br>};<br><br>const first = something(&#39;first&#39;);<br>const second = something(&#39;second&#39;);<br><br>first(); // logs random number<br>second(); // logs another random number</pre><p>This is like taking a photograph of a dynamic scene: as soon as you press the button, the entire scene is forever “frozen” in the photograph. Pressing the button again won’t change anything in the previously taken photo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hNjSyvofsmRQXQ_ZB9fsIA.png" /></figure><p>In React, we are constantly creating closures, often without even realizing it. Every callback function declared within a component is a closure:</p><pre>const Component = () =&gt; {<br>  const onClick = () =&gt; {<br>    // closure!<br>  };<br><br>  return &lt;button onClick={onClick} /&gt;;<br>};</pre><p>Everything inside useEffect or useCallback hooks is a closure:</p><pre>const Component = () =&gt; {<br>  const onClick = useCallback(() =&gt; {<br>    // closure!<br>  });<br><br>  useEffect(() =&gt; {<br>    // closure!<br>  });<br>};</pre><p>They all can access the state, props, and local variables declared within the component:</p><pre>const Component = () =&gt; {<br>  const [state, setState] = useState();<br><br>  const onClick = useCallback(() =&gt; {<br>    // perfectly fine<br>    console.log(state);<br>  });<br><br>  useEffect(() =&gt; {<br>    // perfectly fine<br>    console.log(state);<br>  });<br>};</pre><p>Every function inside a component is a closure, because the component itself is just a function.</p><h3>The Problem with Stale Closures</h3><p>However, all of the above, if you haven’t encountered closures before, might seem novel but is actually quite simple. The more functions you create, the more natural it becomes. We’ve been writing React for so long without even needing to understand the concept of “closures.”</p><p>So, where is the problem? Why are closures one of the most daunting things in JavaScript and cause so much pain for many developers?</p><p>Because as long as there is a reference to the function causing the closure, the closure will continue to exist. And the reference to a function is just a value that can be assigned to anything.</p><p>For example, this function, it returns a completely innocent closure:</p><pre>const something = (value) =&gt; {<br>  const inside = () =&gt; {<br>    console.log(value);<br>  };<br><br>  return inside;<br>};</pre><p>The problem is that each call recreates the inner function. What happens if I decide to try caching it? Something like this:</p><pre>const cache = {};<br><br>const something = (value) =&gt; {<br>  if (!cache.current) {<br>    cache.current = () =&gt; {<br>      console.log(value);<br>    };<br>  }<br><br>  return cache.current;<br>};</pre><p>At first glance, there doesn’t seem to be anything wrong with this code. We just created an external variable named cache and assigned the inner function to the cache.current property. Then, we won’t recreate this function every time; instead, we directly return the already saved value.</p><p>However, if we try calling it multiple times, we will notice a strange phenomenon:</p><pre>const first = something(&#39;first&#39;);<br>const second = something(&#39;second&#39;);<br>const third = something(&#39;third&#39;);<br><br>first(); // logs &quot;first&quot;<br>second(); // logs &quot;first&quot;<br>third(); // logs &quot;first&quot;</pre><p>No matter how many times we call the something function with different arguments, the recorded value is always the first argument!</p><p>We have just created what’s known as a “stale closure.” Each closure is frozen at the time of its creation. When we first call the something function, we create a closure that contains the value &quot;first&quot; in a variable. Then, we save it in an object outside the something function.</p><p>When we call the something function the next time, we return the previously created closure, instead of creating a new function with a new closure. This closure will forever be frozen together with the &quot;first&quot; variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0QpscQ_ERXeXE1dj82T3AQ.png" /></figure><p>To fix this issue, we can recreate the function and its closure every time the value changes, something like this:</p><pre>const cache = {};<br>let prevValue;<br><br>const something = (value) =&gt; {<br>  // check whether the value has changed<br>  if (!cache.current || value !== prevValue) {<br>    cache.current = () =&gt; {<br>      console.log(value);<br>    };<br>  }<br><br>  // refresh it<br>  prevValue = value;<br>  return cache.current;<br>};</pre><p>Save the value in a variable so that we can compare the next value with the previous one. If the variable changes, refresh the cache.current closure. Now, it will correctly print the variable, and if we compare functions with the same value, the comparison will return true:</p><pre><br>const first = something(&#39;first&#39;);<br>const anotherFirst = something(&#39;first&#39;);<br>const second = something(&#39;second&#39;);<br><br>first(); // logs &quot;first&quot;<br>second(); // logs &quot;second&quot;<br>console.log(first === anotherFirst); // will be true</pre><h3>Stale Closures in React: useCallback</h3><p>We just implemented a functionality almost identical to the useCallback hook! Every time we use useCallback, we create a closure and cache the function passed to it:</p><pre>// that inline function is cached exactly as in the section before<br>const onClick = useCallback(() =&gt; {<br>  <br>}, []);</pre><p>If we need to access state or props within this function, we need to add them to the dependency array:</p><pre>const Component = () =&gt; {<br>  const [state, setState] = useState();<br><br>  const onClick = useCallback(() =&gt; {<br>    // access to state inside<br>    console.log(state);<br><br>    // need to add this to the dependencies array<br>  }, [state]);<br>};</pre><p>This dependency array allows React to refresh the cached closure, just as we did when comparing value !== prevValue. If I forget this array, our closure will become stale:</p><pre>const Component = () =&gt; {<br>  const [state, setState] = useState();<br><br>  const onClick = useCallback(() =&gt; {<br>    // state will always be the initial state value here<br>    // the closure is never refreshed<br>    console.log(state);<br><br>    // forgot about dependencies<br>  }, []);<br>};</pre><p>Each time we trigger this callback, everything that will be printed is undefined.</p><h3>Stale Closures in React: Refs</h3><p>After the useCallback and useMemo hooks, the second most common way to introduce stale closures is through Refs.</p><p>What happens if I try to use a Ref for the onClick callback instead of the useCallback hook? Some articles suggest doing this to memoize props on a component. On the surface, it does seem simpler: just pass a function to useRef and access it through ref.current, with no dependencies to worry about.</p><pre>const Component = () =&gt; {<br>  const ref = useRef(() =&gt; {<br>    // click handler<br>  });<br><br>  // ref.current stores the function and is stable between re-renders<br>  return &lt;HeavyComponent onClick={ref.current} /&gt;;<br>};</pre><p>However, every function inside a component forms a closure, including the function we pass to useRef. Our ref is only initialized once when created and does not update itself. This is basically the logic we created at the beginning, except we&#39;re passing not a value, but the function we want to retain. Like this:</p><pre>const ref = {};<br><br>const useRef = (callback) =&gt; {<br>  if (!ref.current) {<br>    ref.current = callback;<br>  }<br><br>  return ref.current;<br>};</pre><p>Therefore, in this case, the closure formed at the beginning (when the component is first initialized) will be retained and never refreshed. When we try to access the state or props inside the function stored in the Ref, we can only get their initial values:</p><pre>const Component = ({ someProp }) =&gt; {<br>  const [state, setState] = useState();<br><br>  const ref = useRef(() =&gt; {<br>    // both of them will be stale and will never change<br>    console.log(someProp);<br>    console.log(state);<br>  });<br>};</pre><p>To solve this problem, we need to ensure that the ref value updates every time the content we are trying to access changes. Essentially, we need to implement what the dependency array in the useCallback hook does.</p><pre>const Component = ({ someProp }) =&gt; {<br>  // initialize ref - creates closure!<br>  const ref = useRef(() =&gt; {<br>    // both of them will be stale and will never change<br>    console.log(someProp);<br>    console.log(state);<br>  });<br><br>  useEffect(() =&gt; {<br>    // update the closure when state or props change<br>    ref.current = () =&gt; {<br>      console.log(someProp);<br>      console.log(state);<br>    };<br>  }, [state, someProp]);<br>};</pre><h3>Stale Closures in React: React.memo</h3><p>Finally, we return to the beginning of the article, back to the mystery that started it all. Let’s take another look at the problematic code:</p><pre>const HeavyComponentMemo = React.memo(<br>  HeavyComponent,<br>  (before, after) =&gt; {<br>    return before.title === after.title;<br>  },<br>);<br><br>const Form = () =&gt; {<br>  const [value, setValue] = useState();<br><br>  const onClick = () =&gt; {<br>    // submit our form data here<br>    console.log(value);<br>  };<br><br>  return (<br>    &lt;&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        value={value}<br>        onChange={(e) =&gt; setValue(e.target.value)}<br>      /&gt;<br>      &lt;HeavyComponentMemo<br>        title=&quot;Welcome to the form&quot;<br>        onClick={onClick}<br>      /&gt;<br>    &lt;/&gt;<br>  );<br>};</pre><p>Every time the button is clicked, it prints “undefined”. The value in onClick never updates, can you tell me why?</p><p>Of course, this is another case of a stale closure. When we create onClick, it first forms a closure with the default state value (undefined). We pass this closure along with the title property to our Memo component. In the comparison function, we only compare the title. It never changes; it&#39;s just a string. The comparison function always returns true, HeavyComponent never updates, and therefore, it holds a reference to the first onClick closure with the frozen undefined value.</p><p>Now that we know the problem, how do we solve it? Easier said than done…</p><p>Ideally, we should compare every prop in the comparison function, so we need to include onClick:</p><pre>(before, after) =&gt; {<br>  return (<br>    before.title === after.title &amp;&amp;<br>    before.onClick === after.onClick<br>  );<br>};</pre><p>However, in this case, this means we’re just re-implementing React’s default behavior, doing the same thing as React.memo without a comparison function. Therefore, we can abandon it and just keep React.memo(HeavyComponent).</p><p>But doing so means we need to wrap onClick in useCallback. But since it depends on state, we&#39;re back to square one: every time the state changes, our HeavyComponent will re-render, which is exactly what we wanted to avoid.</p><p>We could try many other methods, but we don’t have to do any major restructuring to escape the closure trap. There’s a cool trick that can help us.</p><h3>Escaping the Closure Trap Using Refs</h3><p>Let’s temporarily move away from the comparison function in React.memo and onClick implementation. We just need a pure component with state and a memoized HeavyComponent:</p><pre>const HeavyComponentMemo = React.memo(HeavyComponent);<br><br>const Form = () =&gt; {<br>  const [value, setValue] = useState();<br><br>  return (<br>    &lt;&gt;<br>        &lt;input type=&quot;text&quot; value={value} onChange={(e) =&gt; setValue(e.target.value)} /&gt;<br>        &lt;HeavyComponentMemo title=&quot;Welcome to the form&quot; onClick={...} /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>Now we need to add an onClick function that remains stable during re-renders but can also access the latest state without needing to be recreated. We&#39;ll store it in a Ref, so for now, we add an empty one:</p><pre>const Form = () =&gt; {<br>  const [value, setValue] = useState();<br><br>  // adding an empty ref<br>  const ref = useRef();<br>};</pre><p>To allow the function to access the latest state, it needs to be recreated on every re-render, which is unavoidable. This is the nature of closures and is unrelated to React. We should modify the Ref in useEffect, not directly in the render, so we can do it like this:</p><pre>const Form = () =&gt; {<br>  const [value, setValue] = useState();<br><br>  // adding an empty ref<br>  const ref = useRef();<br><br>  useEffect(() =&gt; {<br>    // our callback that we want to trigger<br>    // with state<br>    ref.current = () =&gt; {<br>      console.log(value);<br>    };<br><br>    // no dependencies array!<br>  });<br>};</pre><p>A useEffect without a dependency array triggers on every re-render. This is exactly what we want, so now in our ref.current, we have a closure that is recreated on every re-render, and therefore the printed state is always up-to-date.</p><p>But we can’t pass ref.current directly to the memoized component. This value will be different on every re-render, and memoization will not work.</p><pre>const Form = () =&gt; {<br>  const ref = useRef();<br><br>  useEffect(() =&gt; {<br>    ref.current = () =&gt; {<br>      console.log(value);<br>    };<br>  });<br><br>  return (<br>    &lt;&gt;<br>      {/* Can&#39;t do that, will break memoization */}<br>      &lt;HeavyComponentMemo onClick={ref.current} /&gt;<br>    &lt;/&gt;<br>  );<br>};</pre><p>So, we create an empty function wrapped in useCallback that does not depend on this function.</p><pre>const Form = () =&gt; {<br>  const ref = useRef();<br><br>  useEffect(() =&gt; {<br>    ref.current = () =&gt; {<br>      console.log(value);<br>    };<br>  });<br><br>  const onClick = useCallback(() =&gt; {<br>    // empty dependency! will never change<br>  }, []);<br><br>  return (<br>    &lt;&gt;<br>      {/* Now memoization will work, onClick never changes */}<br>      &lt;HeavyComponentMemo onClick={onClick} /&gt;<br>    &lt;/&gt;<br>  );<br>};</pre><p>Now, memoization can work perfectly because onClick never changes. But there&#39;s a problem: it doesn&#39;t do anything.</p><p>Here’s a magical trick: we just need to call ref.current in the memoized callback:</p><pre>useEffect(() =&gt; {<br>  ref.current = () =&gt; {<br>    console.log(value);<br>  };<br>});<br><br>const onClick = useCallback(() =&gt; {<br>  // call the ref here<br>  ref.current();<br><br>  // still empty dependencies array!<br>}, []);</pre><p>Notice how the ref is not in the dependency array of useCallback? The ref itself does not change. It&#39;s just a reference to a mutable object returned by the useRef hook. However, when a closure freezes everything around it, it does not make the object immutable or frozen. Objects are stored in a different part of memory, and multiple variables can contain references to the exact same object.</p><pre>const a = { value: &#39;one&#39; };<br>// b is a different variable that references the same object<br>const b = a;</pre><p>If I change the object through one reference and then access it through another, the change will be visible:</p><pre>a.value = &#39;ConardLi&#39;;<br><br>console.log(b.value); // will be &quot;ConardLi&quot;</pre><p>In our case, this situation does not occur: we have the exact same reference in both useCallback and useEffect. Therefore, when we change the current property of the ref object in useEffect, we can access that property in useCallback, which happens to be a closure that has captured the latest state data. The complete code is as follows:</p><pre>const Form = () =&gt; {<br>  const [value, setValue] = useState();<br>  const ref = useRef();<br><br>  useEffect(() =&gt; {<br>    ref.current = () =&gt; {<br>      // will be latest<br>      console.log(value);<br>    };<br>  });<br><br>  const onClick = useCallback(() =&gt; {<br>    // will be latest<br>    ref.current?.();<br>  }, []);<br><br>  return (<br>    &lt;&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        value={value}<br>        onChange={(e) =&gt; setValue(e.target.value)}<br>      /&gt;<br>      &lt;HeavyComponentMemo<br>        title=&quot;你好 code秘密花园&quot;<br>        onClick={onClick}<br>      /&gt;<br>    &lt;/&gt;<br>  );<br>};</pre><p>Now, we achieve the best of both worlds: the Heavy component is appropriately memoized and does not re-render with every state change. Its onClick callback can access the latest data in the component without breaking memoization. Now, we can safely send everything needed to the backend!</p><p>In Conclusion Let’s summarize the key points mentioned in this article:</p><ol><li>Every time a function is created inside another function, a closure is formed.</li><li>Since React components are just functions, every function created inside them forms a closure, including hooks like useCallback and useRef.</li><li>When a closure-forming function is called, all the data around it gets “frozen,” like a snapshot.</li><li>To update this data, we need to recreate the “closure” function. This is what the dependencies in hooks like useCallback allow us to do.</li><li>If we miss dependencies, or do not refresh the closure function assigned to ref.current, the closure becomes &quot;stale.&quot;</li><li>In React, we can take advantage of the fact that Ref is a mutable object to escape the problem of “stale closures.” We can change ref.current outside of the stale closure and then access it within the closure to get the latest data.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d243c67f8a8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build your own Vue3 Components library]]></title>
            <link>https://medium.com/@lovexctk/build-your-own-vue3-components-library-3afa62cec162?source=rss-c5b4ba7fd4b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3afa62cec162</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[components]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[xctk]]></dc:creator>
            <pubDate>Tue, 12 Dec 2023 09:09:17 GMT</pubDate>
            <atom:updated>2024-04-23T06:44:08.621Z</atom:updated>
            <content:encoded><![CDATA[<h3>Preparation</h3><p>the most popular way to build component libraries is to use monorepo, which has many benefits. It can manage multiple projects in one code warehouse and achieve resource sharing between projects. This method is also used here.</p><h3>Using pnpm</h3><p>First install pnpm global &amp; init</p><pre>pnpm install pnpm -g<br><br>pnpm init</pre><p>After getting the initial content of package.json, delete the name in package.json and add &quot;private&quot;: true property, as this is not meant to be published as a whole. Components are written in the packages directory.</p><pre>{<br>  &quot;private&quot;: true,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo &quot;Error: no test specified&quot; &amp;&amp; exit 1&quot;<br>  },<br>  &quot;keywords&quot;: [],<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;<br>}</pre><h3>Configuring the Monorepo Workspace</h3><p>The current structure directory includes docs for storing component library documentation, examples for debugging written components, and components in packages for storing personal components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*yHDNsvQim9naC12Jp9_fcQ.png" /></figure><p>For example, if using packages and examples, configure both in pnpm-workspace.yaml.</p><pre>packages:<br>  - &#39;packages/**&#39;<br>  - &#39;examples&#39;</pre><p>Each submodule has its own package.json file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*oCSvZi7PdGY52UN0bZkk2g.png" /></figure><p>Taking the package.json of the components package as an example, it includes dependencies like &quot;@uv-ui/hooks&quot;: &quot;workspace:^1.0.0&quot; and &quot;@uv-ui/utils&quot;: &quot;workspace:^1.0.0&quot; which are dependent on other directory packages. If the components package needs to use these two packages, they must also be installed in this directory. When publishing the npm package later, the workspace:^ prefix should be removed. These dependent packages also need to be independently published as npm packages, and this process is described in detail in the section about publishing components.</p><pre>{<br>  &quot;name&quot;: &quot;uv-ui&quot;,<br>  &quot;private&quot;: false,<br>  &quot;version&quot;: &quot;1.0.11&quot;,<br>  &quot;main&quot;: &quot;dist/es/index.js&quot;,<br>  &quot;module&quot;: &quot;dist/es/index.js&quot;,<br>  &quot;style&quot;: &quot;dist/es/style.css&quot;,<br>  &quot;description&quot;: &quot;基于vue3的移动端组件库&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;build&quot;: &quot;vite build&quot;,<br>    &quot;lint&quot;: &quot;eslint ./src/**/*.{js,jsx,vue,ts,tsx} --fix&quot;<br>  },<br>  &quot;repository&quot;: {<br>    &quot;type&quot;: &quot;git&quot;,<br>    &quot;url&quot;: &quot;https://github.com/monsterxwx/uv-ui&quot;,<br>    &quot;directory&quot;: &quot;packages/uv-ui&quot;<br>  },<br>  &quot;keywords&quot;: [<br>    &quot;uv-ui&quot;,<br>    &quot;vue3组件库&quot;,<br>    &quot;mobile&quot;,<br>    &quot;frontend&quot;,<br>    &quot;components&quot;<br>  ],<br>  &quot;files&quot;: [<br>    &quot;dist&quot;<br>  ],<br>  &quot;author&quot;: &quot;coderxwx&quot;,<br>  &quot;license&quot;: &quot;MIT&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;@uv-ui/hooks&quot;: &quot;workspace:^1.0.0&quot;,<br>    &quot;@uv-ui/utils&quot;: &quot;workspace:^1.0.0&quot;<br>  }<br>}</pre><p>The names of the other two packages are @uv-ui/hooks and @uv-ui/utils, and their creation process is the same as previously described.</p><h3>Inter-package Calls within the Repository</h3><p>How do we enable mutual calls between the hooks, utils, and components packages? We simply need to install all three packages into the node_modules directory at the root of the repository. All dependencies are installed in the root directory. To install in the root directory, you need to add -w, which indicates that the installation is for the packages.json of the common module.</p><pre>pnpm install uv-ui -w<br>pnpm install @uv-ui/hooks -w<br>pnpm install @uv-ui/utils -w</pre><p>The package.json in the root directory will show the following dependencies, which are the three packages we just installed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*bmk8_mDYMGkTFDe5xVWpCg.png" /></figure><h3>Component Writing</h3><p>If our component library package needs to support on-demand import, then each component must be registered with Vue using app.component(comp.name, comp). Writing this for each component can be cumbersome, so it can be encapsulated into a function.</p><pre>export const withInstall = (comp) =&gt; {<br>  comp.install = (app) =&gt; {<br>    // register component<br>    app.component(comp.name, comp)<br>  }<br>  return comp<br>}</pre><p>Taking the button component as an example, the directory structure is as follows: write each component under the src directory, and in the components directory, there is an index file used to export all components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*QAr66GcpqbVl89dAu72nIA.png" /></figure><p>The index.js code for the button is as follows: import the written button component and then export it, which allows each component to be loaded on demand.</p><pre>import Button from &#39;./button.vue&#39;<br>import {withInstall} from &#39;@uv-ui/utils&#39;<br><br>const UvButton = withInstall(Button)<br>export default UvButton</pre><p>Now, looking at the index.js file in the components directory, import as many components as there are, and then export them all. The purpose of this is to enable direct import of components during full import, and then using vue.use(uv-ui) to register all components.</p><pre>import uvButton from &#39;./button&#39;<br><br>const components = [<br>  uvButton<br>]<br><br>const install = (Vue) =&gt; {<br>  components.forEach(component =&gt; {<br>    Vue.component(component.name, component)<br>  })<br>}<br><br>export {<br>  uvButton<br>}<br><br>export default install</pre><p>Let’s take a look at the button.vue file. Since there&#39;s quite a bit of code, we&#39;ll omit some parts and only keep the key elements.</p><p>You can see that each component needs to be given a name for convenient registration in Vue, like export default { name: &#39;UvButton&#39; }. Additionally, styles are abstracted through CSS variables to facilitate easy modifications. It&#39;s not necessary to add a scoped scope to the styles; simply naming the style names appropriately is sufficient. The same applies to other components.</p><pre>&lt;template&gt;<br>  &lt;div class=&quot;uv-button&quot;&gt;<br>    <br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script setup&gt;<br>export default {<br>  name: &#39;UvButton&#39;<br>}<br>&lt;/script&gt;<br><br>&lt;style lang=&quot;scss&quot;&gt;<br>:root {<br>  --uv-button-primary: #409eff;<br>  --uv-button-success: #67c23a;<br>  --uv-button-warning: #e6a23c;<br>  --uv-button-error: #f56c6c;<br>  --uv-button-info: #909399;<br>  --uv-button-text: #303133;<br>}<br>$primary: var(--uv-button-primary);<br>$success: var(--uv-button-success);<br>$warning: var(--uv-button-warning) ;<br>$error: var(--uv-button-error) ;<br>$info: var(--uv-button-info) ;<br>$text: var(--uv-button-text) ;<br>.uv-button {<br>  font-size: var(--uv-button-font-size);<br>  border: 0;<br>  border-radius: var(--uv-button-border-radius);<br>  white-space: nowrap;<br>  color: #ffffff;<br>  background: none;<br>  outline: none;<br>  cursor: pointer;<br>}<br>&lt;/style&gt;<br><br></pre><h3>Component Bundling</h3><p>For component bundling, we utilize the library mode provided by Vite. Unlike tools like gulp, this is a relatively simple bundling method that requires minimal configuration. It allows each component to be bundled independently. Currently, after bundling, all component styles are combined into a single style.css file, which means all styles need to be imported. Components are imported on demand, but if you want to separate the styles as well, you would need to use tools like gulp. This would involve splitting out all the styles into a separate package, such as theme-chalk, and then importing them in a similar manner to how it&#39;s done in element-ui. While this process is more involved, I won&#39;t go into detail here. You can find relevant articles for a deeper understanding.</p><pre>import { defineConfig } from &#39;vite&#39;<br>import vue from &#39;@vitejs/plugin-vue&#39;<br>export default defineConfig({<br>  build: {<br>    target: &#39;modules&#39;,<br>    // 压缩<br>    minify: true,<br>    rollupOptions: {<br>      // 忽略打包vue文件<br>      external: [&#39;vue&#39;],<br>      input: [&#39;src/index.js&#39;],<br>      output: [<br>        {<br>          format: &#39;es&#39;,<br>          entryFileNames: &#39;[name].js&#39;,<br>          preserveModules: true,<br>          // 配置打包根目录<br>          dir: &#39;dist/es&#39;,<br>          preserveModulesRoot: &#39;src&#39;<br>        },<br>        {<br>          format: &#39;cjs&#39;,<br>          entryFileNames: &#39;[name].js&#39;,<br>          preserveModules: true,<br>          dir: &#39;dist/lib&#39;,<br>          preserveModulesRoot: &#39;src&#39;<br>        }<br>      ]<br>    },<br>    lib: {<br>      entry: &#39;./index.js&#39;,<br>      formats: [&#39;es&#39;, &#39;cjs&#39;]<br>    }<br>  },<br>  plugins: [<br>    vue()<br>  ]<br>})</pre><p>Below is the structure after bundling, with separate directories for es and lib, and the styles located in style.css within the es directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*nTpXcSp7cAMTEbAA" /></figure><p>The usage methods are quite straightforward.</p><p>First : Full usage by importing in main.js</p><pre>import uvUI from &#39;uv-ui&#39;<br>import &#39;uv-ui/dist/es/style.css&#39;<br><br><br>app.use(uvUI)</pre><p>Second : On-demand import by including the style file in main.js</p><pre>import &#39;uv-ui/dist/es/style.css&#39;</pre><p>For other places where the components are used, simply import the relevant components.</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;uvButton type=&quot;primary&quot;&gt;toggle&lt;/uvButton&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br>&lt;script setup&gt;<br>import { uvButton } from &#39;uv-ui&#39;<br>&lt;/script&gt;</pre><h3>Publishing Components</h3><p><strong>Writing the </strong><strong>package.json</strong></p><p>Explanation of important fields in package.json:</p><p>name: This is the name of your npm project package. When you publish it to npm, this name will be used. Choose a semantically meaningful name that does not conflict with existing npm libraries.</p><p>private: Whether the package is private or not. To publish to npm, you need to set this to false.</p><p>version: The version number. When updating an npm package, you must modify it to a higher version number before successfully publishing to npm. It&#39;s best to follow the npm version management specifications for version numbers.</p><p>description: A description of the package. After publishing to npm, when you search for this npm package, it will be displayed below the package name in the search suggestions as a descriptive note.</p><p>main: The entry file path. When you import or require this npm package using import or require, it will be the file at this path that is imported.</p><p>keywords: The keywords for this package.</p><p>files: A whitelist of directories that specifies which files will be uploaded to the npm package. Some files, such as package.json, LICENSE, README.md, etc., are always uploaded and cannot be controlled.</p><p>repository: The associated GitHub address.</p><p>package.json ：</p><pre>{<br>  &quot;name&quot;: &quot;uv-ui&quot;,<br>  &quot;private&quot;: false,<br>  &quot;version&quot;: &quot;1.0.11&quot;,<br>  &quot;main&quot;: &quot;dist/es/index.js&quot;,<br>  &quot;module&quot;: &quot;dist/es/index.js&quot;,<br>  &quot;style&quot;: &quot;dist/es/style.css&quot;,<br>  &quot;description&quot;: &quot;ui component for mobile base on vue3&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;build&quot;: &quot;vite build&quot;,<br>    &quot;lint&quot;: &quot;eslint ./src/**/*.{js,jsx,vue,ts,tsx} --fix&quot;<br>  },<br>  &quot;repository&quot;: {<br>    &quot;type&quot;: &quot;git&quot;,<br>    &quot;url&quot;: &quot;https://github.com/monsterxwx/uv-ui&quot;,<br>    &quot;directory&quot;: &quot;packages/uv-ui&quot;<br>  },<br>  &quot;keywords&quot;: [<br>    &quot;uv-ui&quot;,<br>    &quot;vue3组件库&quot;,<br>    &quot;mobile&quot;,<br>    &quot;frontend&quot;,<br>    &quot;components&quot;<br>  ],<br>  &quot;files&quot;: [<br>    &quot;dist&quot;<br>  ],<br>  &quot;author&quot;: &quot;coderxwx&quot;,<br>  &quot;license&quot;: &quot;MIT&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;@coderxwx/uv-ui-hooks&quot;: &quot;1.0.0&quot;,<br>    &quot;@coderxwx/uv-ui-utils&quot;: &quot;1.0.0&quot;<br>  }<br>}</pre><h3><strong>Adding a LICENSE</strong></h3><p>Use the current year and replace coderxwx with your name:</p><pre>MIT License<br>Copyright (c) 2023 coderxwx<br>Permission is hereby granted, free of charge, to any person obtaining a copy<br>of this software and associated documentation files (the &quot;Software&quot;), to deal<br>in the Software without restriction, including without limitation the rights<br>to use, copy, modify, merge, publish, distribute, sublicense, and/or sell<br>copies of the Software, and to permit persons to whom the Software is<br>furnished to do so, subject to the following conditions:<br>The above copyright notice and this permission notice shall be included in all<br>copies or substantial portions of the Software.<br>THE SOFTWARE IS PROVIDED &quot;AS IS&quot;, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR<br>IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,<br>FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE<br>AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER<br>LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,<br>OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE<br>SOFTWARE.</pre><h3>Registering and Logging in to npm Account</h3><p>To publish to npm, you first need to register an npm account. You can register through the official website at [http://www.npmjs.com][1].</p><p>npm login</p><p>To log in to npm, enter the command npm login. Then input your username and password. Note that your password input will not be displayed, but you can enter it normally. After that, enter your email address, and once the email verification code is successfully verified, you will be logged in. You will not need to repeat this login process in the future.</p><h3>npm debug</h3><p>If you do not need to debug, you can skip the debugging steps and proceed directly to publishing.</p><p>From the root directory of your npm project, run the following terminal command. This will add the npm package to your local npm cache:</p><pre>npm link</pre><p>If you want to reference and debug the package in another project (for example, a project named “aaa”), you only need to run the following command within the “aaa” project directory:</p><pre>npm link package-name</pre><p>To unlink the project “aaa” from the npm package, run the following command within the “aaa” project directory:</p><pre>npm unlink package-name</pre><p>To prevent any confusion or conflicts between locally debugging the npm package and the published version, remember to manually unlink the project after debugging is complete.<strong>Publishing the Component</strong></p><p>Run the publish command from the root directory of your npm package：</p><pre>npm publish</pre><p>After the operation is finished, you can search for the published npm package on the npm official website after a while.</p><p><strong>Common Errors During Publishing</strong></p><ul><li><strong>403 Error</strong>: Ensure you’re using the official npm registry, that you’re logged in correctly, and that the package name is unique.</li><li><strong>402 Error</strong>: Occurs when publishing a scoped package. Use npm publish --access=public to publish a public package.</li><li><strong>404 Error</strong>: Typically related to scope issues. Ensure the path and scope are correct.</li></ul><h3><strong>Publishing Private Packages</strong></h3><p>When writing a component library, we will use some functions, which can be published as a package. However, they do not need to be published as official packages, but only for the main package of the component library, for instance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*Fd0DQ5ACww11n7DA" /></figure><p>In package.json, if the name field uses the @xx format, it represents a private package. Publishing a private package to npm requires payment. However, we can configure the publishConfig field to indicate it as a public package and then use npm publish to release it. If you don&#39;t want to write this configuration, you can directly input npm publish --access=public. For example, my private package has the prefix @coderxwx, where @ is followed by your npm username.</p><pre>{<br>  &quot;name&quot;: &quot;@coderxwx/uv-ui-hooks&quot;,<br>  &quot;private&quot;: false,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo &quot;Error: no test specified&quot; &amp;&amp; exit 1&quot;<br>  },<br>  &quot;publishConfig&quot;: {<br>    &quot;access&quot;: &quot;public&quot;,<br>    &quot;registry&quot;: &quot;https://registry.npmjs.org/&quot;<br>  },<br>  &quot;keywords&quot;: [],<br>  &quot;author&quot;: &quot;coderxwx&quot;,<br>  &quot;license&quot;: &quot;MIT&quot;<br>}</pre><p>If you don’t want to use your account name as the prefix for your private package, you can create an organization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/0*QBBeSvKeOOc9zujB" /></figure><p>After creating the organization, you can use its name as the prefix for your packages. For example, if the name of your organization is “uv-ui”, you can then publish your packages using “@uv-ui” as the prefix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*H8TeLlt-sUhquUy5" /></figure><h3><strong>Updating Components</strong></h3><p>After modifying a component, there are two ways to republish and update it. One is to directly modify the version information in the package.json file and then perform npm publish.</p><p>There is also a more standardized approach using npm commands.</p><p>The type options include:</p><p>patch: Minor changes, such as bug fixes, result in a version number change from v1.0.0 to v1.0.1.</p><p>minor: Adding new features without affecting existing functionality leads to a version number change from v1.0.0 to v1.1.0.</p><p>major: Breaking backward compatibility of the module, representing a major version update, results in a version number change from v1.0.0 to v2.0.0.</p><pre>npm version [type]<br><br>npm publish</pre><h3><strong>Documentation</strong></h3><p>Documentation can be built using VitePress, which is straightforward to set up:</p><pre>pnpm install -D vitepress vue</pre><p>For more details on using VitePress, refer to the <a href="https://vitepress.dev/guide/getting-started">official guide</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3afa62cec162" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>