<?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 Thoai Huynh on Medium]]></title>
        <description><![CDATA[Stories by Thoai Huynh on Medium]]></description>
        <link>https://medium.com/@huynhtrongthoai?source=rss-8fec9e0953a7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*8ohC6cEcGj_DpyqP.</url>
            <title>Stories by Thoai Huynh on Medium</title>
            <link>https://medium.com/@huynhtrongthoai?source=rss-8fec9e0953a7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 16:00:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@huynhtrongthoai/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[Messi còn rời Baca thì code React mà bỏ Redux có gì đâu mà bất ngờ !!!]]></title>
            <link>https://huynhtrongthoai.medium.com/messi-c%C3%B2n-r%E1%BB%9Di-baca-th%C3%AC-code-react-m%C3%A0-b%E1%BB%8F-redux-c%C3%B3-g%C3%AC-%C4%91%C3%A2u-m%C3%A0-b%E1%BA%A5t-ng%E1%BB%9D-d650cb06c72?source=rss-8fec9e0953a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d650cb06c72</guid>
            <category><![CDATA[react-query]]></category>
            <category><![CDATA[context-api]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Thoai Huynh]]></dc:creator>
            <pubDate>Sun, 08 Aug 2021 10:00:44 GMT</pubDate>
            <atom:updated>2021-08-08T10:00:44.618Z</atom:updated>
            <content:encoded><![CDATA[<h3>Messi còn rời Baca thì code React mà bỏ Redux có gì đâu mà bất ngờ !!!</h3><p>Chào mọi người, sau một năm Thọi lên núi bế quang tu luyện thì nay mình đã trở lại với tất cả mọi người rồi đây. (-_-) Chuyện là mấy ngày nay, chắc hẳn các bạn đều hay tin là Messi đã rời Barcelona sau gần 21 năm gắn bó. Thông qua sự kiện này, mình bất chợt nhớ đến là từ lâu mình đã không còn sử dụng Redux …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fgCRAIKoC1hXFnwY.jpg" /></figure><h3>Vậy tại sao mà mình đã từ bỏ Redux?</h3><p>Quay lại một xíu về quá khứ, lúc mà React vẫn còn đơn sơ, thì việc quản lý global state của ứng dụng đều do thằng root đảm nhận … Mỗi lần component ông nội muốn gửi state cho component cháu đều phải gửi thông qua component cha.</p><p>Chính điều đó, dẫn đến việc mã code của ta lằn nhằn, rối bời vì props được truyền vào component cha đó sẽ không có ích gì cho bản thân của nó. Vì vậy nó được anh chị giang hồ đồn đại với cái tên là <strong>Prop drilling.</strong></p><blockquote>Nhưng không sao<em>, ở đâu có cái khó, ở đó có Redux</em>. Redux thật sự giúp chúng ta giải quyết vấn đề trên bằng cách tạo ra 1 store chung để quản lý tất cả state của ứng dụng.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*IGyD29mzDvMyoWT4" /></figure><p>Tuy nhiên, khi làm việc với Redux, chúng ta sẽ bắt gặp một vài nhược điểm như sau:</p><ul><li>Tốn quá nhiều thời gian để code, quá nhiều file từ action, reducer, middleware,…</li><li>Chỉ cần 1 thay đổi nhỏ =&gt; Redux sẽ cấu trúc lại DOM =&gt; giảm hiệu suất.</li><li>Không cache state.</li></ul><p>Cứ tưởng Redux cứ mãi trên đỉnh cao thì ông tổ React đã cho ra đời một bộ chiêu thức mới: React Hook + Context API và gần như khắc phục hoàn toàn nhược điểm trên.</p><p>Và từ đó, React như khẳng định lại quan điểm: “Thà ta phụ người thiên hạ, chứ không để Redux chiếm thị phần của ta”.</p><h3>Bộ chiêu thức React-hook với Context API sẽ thi triển như thế nào?</h3><p>Để build một ứng dụng React, đơn giản nhất là chỉ cần sử dụng useReducer và useContext.</p><ul><li>useReducer: nhận vào reducer và initialState khởi tạo ban đầu, trả về state hiện tại và dispatch function dùng để trigger 1 action.</li><li>useContext: là một hooks trong React Hooks cho phép chúng ta có thể làm việc với React Context trong một functional component.</li></ul><p>Các bạn nếu muốn hiểu rõ nó là gì thì có thể ghé thăm bài này của mình: <a href="https://huynhtrongthoai.medium.com/reactjs-understand-the-nature-of-hook-in-react-8b0d73563e33">https://huynhtrongthoai.medium.com/reactjs-understand-the-nature-of-hook-in-react-8b0d73563e33</a></p><p>Sau đây là cách implement cơ bản trong một component:</p><pre>// TodoApp.js<br>import { useReducer, createContext, useMemo } from &#39;react&#39;;<br>import AddTodo from &#39;./AddTodo&#39;;<br>import TodoList from &#39;./TodoList&#39;;<br><br>export const AppContext = createContext(null);<br><strong>const cache = {};</strong><br><br>export default function TodoApp() {<br>  const [state, dispatch] = useReducer(reducer, cache.state || initialState);</pre><pre>  <strong>cache.state = state;</strong></pre><pre>  const actions = useMemo(() =&gt; ({<br>    setInput: (value) =&gt; {<br>      dispatch({<br>        type: &#39;SET_INPUT&#39;, <br>        payload: value<br>      })<br>    },<br>    addTodo: ({ id, content }) =&gt; {<br>      dispatch({<br>        type: &#39;ADD_TODO&#39;,<br>        payload: { id, content }<br>      })<br>    }<br>  }), []);</pre><pre>  return (<br>    &lt;AppContext.Provider value={[state, actions]}&gt;<br>      &lt;div className=&quot;todo-app&quot;&gt;<br>        &lt;h1&gt;{state.title}&lt;/h1&gt;<br>        &lt;input value={state.input} onChange={e =&gt; actions.setInput(e.target.value)} /&gt;<br>        &lt;AddTodo /&gt;<br>        &lt;TodoList /&gt;<br>      &lt;/div&gt;<br>    &lt;/AppContext&gt;<br>  );<br>}</pre><p>Tuy nhiên, khi làm với <strong>context</strong> ta cần chú ý rằng: “Chỉ cần một giá trị trong contextProvider bị thay đổi thì toàn bộ các component trong context đều render lại.</p><p>Và ta sẽ giải quyết vấn đề bằng cách sử dụng useMemo để memorize component.</p><pre>// AddTodo.js<br>import { useContext, memo } from &#39;react&#39;;<br>import { appContext } from &#39;./TodoApp&#39;;<br><br>const genId = () =&gt; Math.rand();<br><br>export default const AddTodo = () =&gt; {<br>  const [state, actions] = useContext(appContext);</pre><pre>  return <strong>useMemo</strong>(() =&gt; {<br>    function handleAddTodo() {<br>      if (content) {<br>        actions.addTodo({ id: genId(), content: input });<br>        actions.setInput(&#39;&#39;);<br>      }<br>    }<br>    return  (<br>      &lt;button onClick={handleAddTodo}&gt;<br>        Add Todo<br>      &lt;/button&gt;<br>    );<br>  }, [state.input, actions])<br>}</pre><p>Như vậy, ta đã có thể dễ dàng thay thế redux rồi phải không nào? Tuy nhiên mình có một số lưu ý khi làm việc với Hook + Context.</p><ul><li>Bạn không nên tiếp cận Context để giải quyết mọi vấn đề chia sẻ state.</li><li>Context KHÔNG nhất thiết phải chung cho toàn bộ ứng dụng mà có thể được áp dụng cho từng module, từng phần riêng lẻ.</li><li>Bạn có thể (và có lẽ nên) có nhiều context được phân tách hợp lý trong ứng dụng của mình.</li></ul><h3><strong>Vậy khi thao tác với API thì phải tạo rất nhiều state như data, loading, errors?</strong></h3><p>Lúc này, có lẽ chúng ta nên nhờ vào một thư viện phù hợp hơn với Hook. Mình biết có 3 thư viện mà support cho vấn đề này.</p><ul><li>React-Query (<strong>recommend</strong>): mình sẽ phân tích nó trong bài tiếp theo.</li><li>SWR: khá giống với React-Query với sự đỡ đầu của NextJS.</li><li>Apollo Client: cú pháp tương tự như React-Query.</li></ul><blockquote>Điểm khác biệt là Apollo Cient sẽ làm việc với GraphQL còn React-Query và SWR sẽ làm việc với REST API.</blockquote><h3>Tổng kết</h3><p>Cuối cùng chúng ta đã hiểu tại sao mà Redux đang dần bị thay thế bởi Hook và Context API. Thông qua đó, ta cũng đã biết được cách để quản lý state ứng dụng mà không cần đến Redux.</p><p>Hy vọng bài viết này thực sự hữu ích với các bạn.</p><blockquote><strong>Nếu các bạn thấy hay, xin cho mình vài like để tạo động lực cho mình làm các bài tiếp theo ạ !!! Cảm ơn mọi người rất nhiều ❤</strong></blockquote><p>Tài liệu tham khảo: <a href="https://dev.to/ipshot/enhancing-usereducer-38ba">https://dev.to/ipshot/enhancing-usereducer-38ba</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d650cb06c72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mobx có thật sự tốt để thay thế cho Redux? (part 1)]]></title>
            <link>https://huynhtrongthoai.medium.com/mobx-c%C3%B3-th%E1%BA%ADt-s%E1%BB%B1-t%E1%BB%91t-%C4%91%E1%BB%83-thay-th%E1%BA%BF-cho-redux-part-1-433fd8a02b2c?source=rss-8fec9e0953a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/433fd8a02b2c</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[mobx]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[single-page-applications]]></category>
            <dc:creator><![CDATA[Thoai Huynh]]></dc:creator>
            <pubDate>Tue, 28 Jul 2020 07:45:17 GMT</pubDate>
            <atom:updated>2021-06-27T06:35:31.624Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mobx có thật sự tốt để thay thế cho Redux?</h3><p>Xin chào các bạn đã trở lại với series tìm hiểu lập trình của Thọi. Hôm nay, mình sẽ giới thiệu cho các bạn biết về một thứ mà mình chắc là ai trong số chúng ta cũng đã từng một lần nghe qua. Đó chính là Mobx — thứ mà mình cảm nhận nó thật sự magic khi vừa mới tiếp cận gần đây.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SMqjtDJ1TcZUdF5W" /></figure><h3><strong>Vậy đã có Redux, sao Mobx còn ra đời chi?</strong></h3><p>Đầu tiên, quay trở lại một chút về Redux. Ngày xưa, khi mình mới bắt đầu học React thì việc quản lý state là đều do component quản lý. Chính vì vậy, việc quản lý một đống state đối với mình là vô cùng khủng khiếp. Từ component cha mà muốn truyền props xuống component con thì phải thông qua từng level, dẫn đến việc khai báo component vô cùng dài dòng. (Sau này cũng có React Context API hỗ trợ việc này)</p><p>Khoảng vài tháng tìm hiểu, mình biết được một thằng quản lí state vô cùng chất lượng mà người ta gọi nó là Redux… Lúc đầu, đọc khái niệm Redux phải nói là muốn tẩu hỏa nhập ma. Nó vừa dài dòng, vừa khó hiểu lại còn quá nhiều các quy tắc. Tuy nhiên, sau khi mình thực hiện vài project thì dần dần mình cũng đã từng bước nắm vững về nó.</p><p>Mình chợt nhận ra rằng, thay vì state do chính component quản lý, ta có thể gom các state vào một store duy nhất và component nào cần sử dụng thì chỉ cần lấy trong store ra là được =&gt; Quá tiện dụng phải không nào. Ngoài ra, có thể nói bản chất của Redux là immutable (nghĩa là nó sẽ nhận vào một state để trả về một state mới) và điều đó rất khó tiếp cận với các bạn không hiểu rõ tính chất reference trong JS. Nếu như bạn không quản lý tốt store của redux thì việc component tự động re-render là một điều không thể tránh khỏi hay những lúc mà ta không hiểu tại sao đã gọi action rồi mà component không re-render.</p><p>Những những bất cập đó mà thằng Mobx nổi lên như một giải pháp thay thế Redux để quản lý state trong ứng dụng. Vậy Mobx khác Redux ở chỗ nào mà nó có thể được người dùng chấp nhận và sử dụng?</p><h3>Sự khác biệt cơ bản giữa Mobx và Redux?</h3><ul><li>Redux sử dụng 1 store để quản lý state trong khi Mobx có thể sử dụng nhiều store sao cho bản thân thấy hiệu quả nhất có thể.</li><li>Như đã nói, Redux là immuatable trong khi Mobx chỉ là mutable (ta có thể thay đổi trực tiếp giá trị)</li><li>Redux chỉ đơn giản là một nơi để lưu trữ dữ liệu, còn lại muốn component re-render như thế nào thì ta phải tự tay làm việc đó. Không như Redux, Mobx sử dụng observable để lưu dữ liệu và khi thay đổi giá trị observable thì component sẽ tự động re-render do bên dưới Mobx đã thực thi những việc đó giúp ta.</li><li>Một nguyên nhân cuối mà mình nhận ra là chúng ta sẽ code ít hơn, ngắn hơn nếu sử dụng Mobx thay vì Redux.</li></ul><p>Cuối cùng , có thể là còn rất nhiều điểm mà mình đã bỏ sót nhưng trên hết, những điểm mà mình vừa liệt kê phía trên là cơ bản nhất về sự khác biệt giữa Mobx và Redux.</p><p>Sau này, chúng ta sẽ đi sâu hơn vào tìm hiểm thật ra Mobx nó sử dụng những cái gì mà tạo ra magic nhiều đến thế… Let&#39;s go.</p><h4>1. Observable</h4><p>Giá trị observable có thể là primitives values (number, string, boolean, null, undefined), reference values (array, objects, function), plain object, class instance, ES6 Map, Set,… Nó là những giá trị mà component sẽ quan sát để biết có nên re-render hay không? Các bạn có thể tìm hiểu thêm về nó thông qua <a href="https://mobx.js.org/refguide/observable.html">https://mobx.js.org/refguide/observable.html</a></p><pre>const map = observable.map({ name: &quot;Messi&quot; })<br>map.set(&quot;name&quot;, &quot;Ronaldo&quot;) </pre><pre>const list = observable([1,2,3,4])<br>list[2] = 5</pre><h4>2. Observer</h4><p>Chắc là nhiều bạn sẽ nhầm lẫn với observable bên trên. Nhìn thì nó viết tương tự nhau nhưng chức năng của nó thì hoàn toàn không liên quan gì nhau.</p><p>Trong khi <strong>Observable</strong> là đại diện cho các giá trị được component quan sát thì <strong>Observer</strong> là một HOC hay decorator subscribes mà giúp cho component có khả năng quan sát. Kết quả là, component sẽ tự động được render khi những giá trị observables liên quan thay đổi. Ở đây, có 2 packages cho phép sử dụng observer.</p><ul><li>mobx-react: chỉ hỗ trợ cho class component.</li><li>mobx-react-lite: chỉ hỗ trợ cho functional component và kích thước cũng nhỏ hơn rất nhiều.</li></ul><h4>3. Computed</h4><p>Như tên gọi của nó, computed sẽ trả về giá trị mới từ giá trị observable hay giá trị computed khác. Nó giúp chúng ta chỉnh sửa state một cách linh hoạt mà không cần gọi action.</p><p>Khi một component nhận vào một computed value mà khi nó thay đổi giá trị thì component vẫn sẽ re-render. Vì vậy, nếu chúng ta muốn cải thiện performance thì có thể kết hợp với reaction (cái này mình sẽ giới thiệu sau) để cache lại giá trị.</p><p>Vậy để cache lại giá trị của computed, chúng ta sẽ thực hiện như thế nào? Nó tương đối đơn giản khi bạn có thể sử dụng 2 cách sau:</p><ul><li>autorun: khi giá trị computed thay đổi thì gán lại giá trị của nó.</li><li>keep-alive: tốt hơn nhiều mặt so với autorun.</li></ul><pre><strong>class</strong> <strong>OrderLine</strong> {<br>   @observable price = 0<br>   @observable amount = 1      <br>   <br>   <strong>constructor</strong>(price) {<br>      <strong>this</strong>.price = price     <br>   }      <br>   <br>   @computed<br>   <strong>get</strong> total() {    <br>      <strong>return</strong> <strong>this</strong>.price * <strong>this</strong>.amount     <br>   }<br>}</pre><h4><strong>4. Autorun</strong></h4><p>Giống như tên gọi của nó, auto là tự động, run là chạy nghĩa là thuộc tính này sẽ tự động chạy hàm truyền vào ngay lập tức, ngoài ra khi các dependencies thay đổi thì bản thân hàm trong nó cũng được gọi. Nghe có vẻ sao mà giống như computed thế không biết. Tuy nhiên, nghĩ kĩ lại thì ta nhận thấy computed luôn tạo ra một giá trị mới trong khi autorun thì không.</p><p>Ngoài ra, khi bạn muốn dừng autorun thì bạn có thể gán nó cho một giá trị và gọi lại giá trị đó. (Giá trị đó chính là disposer function)</p><pre><strong>var</strong> numbers = observable([1, 2, 3])<br><strong>var</strong> sum = computed(() =&gt; numbers.reduce((a, b) =&gt; a + b, 0)) <br> <br><strong>var</strong> disposer = autorun(() =&gt; console.log(sum.get())) // prints &#39;6&#39; numbers.push(4) // prints &#39;10&#39; <br> <br>disposer() <br>numbers.push(5) // won&#39;t print anything, nor is `sum` re-evaluated</pre><h4>5. When</h4><p>When sẽ nhận vào 2 tham số trong đó tham số thứ hai chỉ chạy khi tham số thứ nhất trả về true.</p><pre>class MyResource {</pre><pre>   @observerble sum = 0</pre><pre>   constructor() {</pre><pre>      when(</pre><pre>         () =&gt; this.sum &gt; 5,</pre><pre><em>         // sum = 6 thì nó mới chạy hàm bên dưới</em></pre><pre>         () =&gt; {}</pre><pre>      )</pre><pre>   }</pre><pre>   setInteval(() =&gt; {</pre><pre>      this.sum++;</pre><pre>   }, 1000);</pre><pre>}</pre><p>Ngoài ra, nếu chúng ta không cung cấp tham số thứ 2 thì mặc định When sẽ trả về một Promise.</p><h4>6. Reaction</h4><p>Được sử dụng rộng rãi nhất là thằng này. Nó được xem là một biến thể của autorun tuy nhiên việc quan sát chi tiết các observable tốt hơn.</p><p>Reaction cũng nhận vào 2 tham số:</p><ul><li>Tham số thứ nhất: quan sát sự thay đổi của các observables và trả về giá trị được sử dụng làm đầu vào của hàm thứ hai.</li><li>Tham số thứ hai: xử lý các side-effect (là các thao tác cần thời gian để phản hồi như call api, đọc ghi file,…).</li></ul><p>Không như autorun, các side-effect này sẽ không được thực thi trực tiếp khi được tạo mà nó phải chờ tham số đầu tiên trả về giá trị mới. Ngoài ra, các observables bên trong function xử lý side-effect này sẽ không được theo dõi.</p><pre><strong>const</strong> todos = observable([     <br>   {<br>      name: &quot;Ronaldo&quot;,         <br>      goal: true,     <br>   },     <br>   {         <br>      name: &quot;Messi&quot;,         <br>      goal: false,     <br>   }, <br>])  </pre><pre>// Sai khi sử dụng reaction: length thay đổi nhưng không theo dõi được name thay đổi! <br><strong>const</strong> reaction1 = reaction(<br>   () =&gt; todos.length,     <br>   (length) =&gt; { <br>       console.log(&quot;reaction 1:&quot;, todos.map((todo) =&gt; todo.name).join(&quot;, &quot;))<br>   }<br>)</pre><pre>//Đúng khi sử dụng reaction: luôn trả về giá trị mới khi name thay đổi<br><strong>const</strong> reaction2 = reaction(     <br>   () =&gt; todos.map((todo) =&gt; todo.name),     <br>   (names) =&gt; console.log(&quot;reaction 2:&quot;, names.join(&quot;, &quot;)) <br>)  </pre><pre><strong>const</strong> autorun1 = autorun(<br>   () =&gt; console.log(&quot;autorun 1:&quot;, todos.map((todo) =&gt;     todo.name).join(&quot;, &quot;)) <br>);  </pre><pre>todos.push({ name: &quot;Neymar&quot;, goal: false }) <br>// reaction 1: Ronaldo, Messi, Neymar<br>// reaction 2: Ronaldo, Messi, Neymar<br>// autorun 1: Ronaldo, Messi, Neymar</pre><pre>todos[0].title = &quot;Degea&quot; <br>// reaction 2: Degea, Messi, Neymar<br>// autorun 1: Degea, Messi, Neymar</pre><h3>Kết luận</h3><p>Vậy là chúng ta đã tìm hiểu những thứ cơ bản trong Mobx rồi. Mình nghĩ chỉ cần nắm vững những thứ vừa nêu ở trên là chúng ta có thể chiến nó một cách ngon lành cành đào. Tuy nhiên, để không phải bắt gặp các tình huống bug khó hiểu hay giảm performance của ứng dụng thì ta phải đào sâu bên trong nó, xem coi cách thức nó hoạt động như thế nào?</p><p>Hy vọng qua bài viết của mình, các bạn đã hiểu phần nào về Mobx. Mình thì cũng mới tìm hiểu Mobx gần đây thôi nhưng mình muốn chia sẻ những gì mình hiểu được cũng như là một cách để bản thân nắm vững kiến thức. Ngoài ra, mình có sai sót hay các bạn có thắc mắc gì thì các bạn có thể comment bên dưới bài viết này.</p><blockquote>Cuối cùng, nếu các bạn thấy bài viết bổ ích, xin đừng ngần ngại thả clap cho mình để mình có động lực làm các bài tiếp theo :))</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=433fd8a02b2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build an application with Webpack (Part 2)]]></title>
            <link>https://huynhtrongthoai.medium.com/build-an-application-with-webpack-part-2-dc617f6a91a?source=rss-8fec9e0953a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc617f6a91a</guid>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Thoai Huynh]]></dc:creator>
            <pubDate>Sat, 20 Jun 2020 07:31:22 GMT</pubDate>
            <atom:updated>2020-06-20T07:31:22.957Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/723/0*C3qcTL9uDpFGB19Q.png" /></figure><p>Today, I have come back to you and we will continue to learn about Webpack. In this section, I want to introduce to you about plugins, optimizations.</p><h4><strong>1. What&#39;s the Plugin?</strong></h4><p>While Loader will transform files one by one, the plugin performs actions or functions on the compilation or chunk.</p><p>To use a plugin, you need to <strong>require()</strong> and add it to array plugins.</p><p>To be honest, when using development/production mode in Webpack we used a lot of default plugins in Webpack.</p><h4>2. Several plugins?</h4><p><strong>a. html-webpack-plugin</strong></p><p>This plugin will generate an HTML5 file for you that includes all your webpack bundles in the body using script tags.</p><p>This is especially useful for webpack bundles that include a hash in the filename which changes every compilation.</p><pre>var HtmlWebpackPlugin = require(&#39;html-webpack-plugin&#39;);<br>var path = require(&#39;path&#39;);<br><br>module.exports = {<br>  entry: &#39;index.js&#39;,<br>  output: {<br>    path: path.resolve(__dirname, &#39;./dist&#39;),<br>    filename: &#39;index_bundle.js&#39;<br>  },<br>  plugins: [new HtmlWebpackPlugin()]<br>};</pre><p><strong>b. clean-webpack-plugin</strong></p><p>This plugin will remove all files inside webpack’s output.path directory, as well as all unused webpack assets after every successful rebuild.</p><p>If using webpack 4+, everything under &lt;PROJECT_DIR&gt;/dist/ will be removed without this plugin.</p><pre>const { CleanWebpackPlugin } <strong>=</strong> require(&#39;clean-webpack-plugin&#39;);</pre><pre>const webpackConfig <strong>=</strong> {<br>  plugins<strong>:</strong> [ <strong>new</strong> CleanWebpackPlugin() ],<br>};</pre><pre>module.exports <strong>=</strong> webpackConfig;</pre><p><strong>c. mini-css-extract-plugin</strong></p><p>This plugin extracts CSS into separate files. It creates a CSS file per JS file which contains CSS. It supports On-Demand-Loading of CSS and SourceMaps.</p><p>It’s recommended to combine mini-css-extract-plugin with the <a href="https://webpack.js.org/loaders/css-loader/">css-loader</a></p><blockquote>It requires webpack 4+ to work. Alternatively, you can use extract-text-webpack-plugin for older versions.</blockquote><p>The reason for using mini-css-extract-plugin<strong>:</strong></p><ul><li>Async loading CSS.</li><li>No duplicate compilation (performance).</li><li>Easier to use</li><li>Specific to CSS</li></ul><pre>const MiniCssExtractPlugin = require(&#39;mini-css-extract-plugin&#39;);<br><br>module.exports = {<br>  plugins: [<br>    new MiniCssExtractPlugin({<br>      filename: &#39;[name].css&#39;,<br>      chunkFilename: &#39;[id].css&#39;,<br>    }),<br>  ],<br>  module: {<br>    rules: [<br>      {<br>        test: /\.css$/,<br>        use: [<br>          {<br>            loader: MiniCssExtractPlugin.loader,<br>            options: {<br>              publicPath: (resourcePath, context) =&gt; {<br>                return path.relative(path.dirname(resourcePath), context) + &#39;/&#39;;<br>              },<br>            },<br>          },<br>          &#39;css-loader&#39;,<br>        ],<br>      },<br>    ],<br>  },<br>};</pre><p><strong>d. uglifyjs-webpack-plugin</strong></p><p>This plugin can take multiple chunks, parse them in sequence, and apply any compression options.</p><pre>module.exports = {<br>  optimization: {<br>    minimizer: [<br>      new UglifyJsPlugin({<br>        cache: true,<br>        parallel: true,<br>        output: {<br>            comments: false,<br>        },      <br>      }),<br>    ],<br>  },<br>};</pre><p><strong>e. HotModuleReplacementPlugin</strong></p><p>Hot Module Replacement (HMR) exchanges, adds, or removes <a href="https://webpack.js.org/concepts/modules/">modules</a> while an application is running, without a full reload.</p><p>HMR should never be used in production and only used in development.</p><pre>new webpack.HotModuleReplacementPlugin({<br>  // Options...<br>});</pre><p>In <em>app.js</em>, <strong>module.hot</strong> will have true value in development and false in production.</p><pre>if (module.hot) {<br>  module.hot.accept()<br>}</pre><p><strong>f. Others</strong></p><ul><li>ManifestPlugin</li><li>InlineChunkHtmlPlugin</li><li>ModuleNotFoundPlugin</li><li>WatchMissingNodeModulesPlugin</li></ul><h4>3. How to optimize performance in Webpack?</h4><p>Although the plugins in Webpack are able to solve performance issues, it is also significant. Therefore, <strong>code splitting</strong> was born to help significantly improve performance.</p><p>It allows us to split code into smaller bundles, which we can download as needed or download in parallel.</p><p>There are 2 types of code splitting that I know:</p><p><strong>a. By entry point</strong></p><p>As the previous post I introduced, Webpack uses entry and output to apply <strong>code splitting.</strong></p><p>However, this is a manual way, so it will not be flexible to divide the code automatically.</p><p>It only supports input files, while imported libraries will still be duplicated. So, we will apply to <strong>prevent duplication</strong> using split chunks in Webpack.</p><p><strong>b</strong>. <strong>By optimization.splitChunks</strong></p><p>This allows us to extract functions, libraries, … into a single entry or create a new chunk.</p><p>Example of using it to cancel duplication of <strong>lodash </strong>library usage inside js files.</p><pre>module.exports = {<br>  optimization: {<br>    splitChunks: {<br>        chunks: &#39;all&#39;<br>    }<br>  },<br>};</pre><p>If you use older versions of Webpack (smaller than version 4), you must use <strong>CommonsChunkPlugin </strong>to replace it.</p><blockquote>According to the webpack documentation, <strong>optimization.splitChunks</strong> has more improvements than <strong>CommonsChunkPlugin</strong>: better cache, Split common chunk more,…</blockquote><h4><strong>In conclusion</strong></h4><p>Webpack is actually quite complex to understand and learn. However, if you want to become a frontend expert then you cannot ignore it</p><blockquote>These are completely my practical experiences. If anything is incorrect, please comment below the post.</blockquote><p>Have a good day!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc617f6a91a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build an application with Webpack (Part 1)]]></title>
            <link>https://huynhtrongthoai.medium.com/build-an-application-with-webpack-part-1-e682c00bc0ce?source=rss-8fec9e0953a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e682c00bc0ce</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[webpack4]]></category>
            <category><![CDATA[babel]]></category>
            <dc:creator><![CDATA[Thoai Huynh]]></dc:creator>
            <pubDate>Wed, 04 Sep 2019 10:17:46 GMT</pubDate>
            <atom:updated>2019-09-04T15:23:58.820Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/723/0*oXl5FePPhdpd-q1z.png" /></figure><p>Today, I will introduce you to a very popular technique now in applications. This is considered a necessary skill to become a good frontend developer. Ok, Let’s start.</p><h4>What is webpack?</h4><p>Today, the logical processing is concentrated in the frontend of the application making the size and ability to load pages become extremely slow. Therefore, webpack was born and is considered a savior for the front-end dev. Webpack is currently the most widely used module bundled with a huge support community and extremely powerful functionality. In short, Webpack is a tool that helps encapsulate the entire program source code as well as images, fonts, and CSS (all of these things called assets) into one file (or several files).</p><h4>How to install webpack?</h4><p>Firstly, you have to create a directory and install a framework to build SPA. I choose react because it is relatively easy to implement.</p><p>After that, I installed a few packages related to webpack:</p><ul><li><strong>Webpack</strong> imports source files into a single bundle file, and it uses loaders to compile different file types.</li><li><strong>Webpack-dev-server</strong> is suitable for development environment. Webpack-dev-server runs on the platform of Express node.js server and runs port 8080.</li><li><strong>Webpack-cli </strong>is suitable for production environment. It is like command line.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*Ox2YZYraoEaq-zEemAK2PA.png" /></figure><p>Here, I will create a folder to config webpack files. Here, I divided them into 3 files for different purposes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*aUTC-Ws905O2GyiPobdsqg.png" /></figure><ul><li>webpack.config.js: It is considered a general config of development and production environments. They can inherit properties from it.</li><li>webpack.dev.js: This is the file to configure webpack for the development environment.</li><li>webpack.prod.js: This is the file to configure webpack for the production environment.</li></ul><p>Then, I will revise scripts in package.json.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qW0MtYKgjqZkj_KTshsKlg.png" /><figcaption>Package.json</figcaption></figure><h4><strong>What does webpack include?</strong></h4><p>We need to understand some of the webpack properties like: entry, output, modules, plugins, resolve, optimization.</p><p>First, in the webpack.config file, I will export it with the options parameter. For each separate environment, the options value will be different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*u_rSJs2JwkilgAqPN3WC6w.png" /><figcaption>Config webpack</figcaption></figure><h4>1. Entry</h4><p>Entry point is the start of webpack. It is the place to declare the file paths in the project which want to be converted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gr7SuyNWEqPBj_labBSFRg.png" /><figcaption>Development</figcaption></figure><p>For development environment, I have used the <strong><em>react-dev-utils / webpackHotDevClient</em></strong> library so that I can connect to WebpackDevServer by a socket and get notified about changes. Instead of the default WebpackDevServer client. This is called hot-reloading.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*Jczd8lRG8rLlH__bA1_Tww.png" /><figcaption>Production</figcaption></figure><h4>2. Output</h4><p>The output is also very easy to understand, it will tell the webpack need to save the file after compiling. However, we do not always have only one single entry, if you have many singles and want to build out multiple outputs, you can apply the naming method as placeholder <strong>[name]</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*c7jRsKP8ksNETKBFsoSxVg.png" /><figcaption>Config webpack</figcaption></figure><p>For development enviroment, I won’t use [hash] for better performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*DVV_wyS64xzNFdR0V9koww.png" /><figcaption>Development</figcaption></figure><p>For production enviroment, I will use [chunkhash] because there is no css file for every single entry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*bMS5QHLIIWujqXCoVvr9bQ.png" /><figcaption>Production</figcaption></figure><p>You can learn more about: [hash], [chunkhash], [contenthash] through:</p><p><a href="https://medium.com/@sahilkkrazy/hash-vs-chunkhash-vs-contenthash-e94d38a32208">Hash vs chunkhash vs ContentHash</a></p><p><a href="https://stackoverflow.com/questions/35176489/what-is-the-purpose-of-webpack-hash-and-chunkhash">https://stackoverflow.com/questions/35176489/what-is-the-purpose-of-webpack-hash-and-chunkhash</a></p><blockquote>The use of [chunkhash] as above is called cache busting. Because the browser will cache the contents of static files like css, js based on the file path. If each build does not change the file name, the example is always style.css. Then the browser will still retrieve the content in the cache based on the old name.</blockquote><p>Then, if you try to run webpack, you will get an error. The reason is that it will not understand the ES6 import syntax. Therefore, we use the loader to solve this situation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NifcARuVi-ff3P9CT_BOLw.png" /></figure><h4>3. Loader</h4><p>Loaders are libraries that will intervene before we import the file, which allows the webpack to expand the ability to not only bundle javascript, but also other static resources, such as css, image, svg, …</p><h4>a. Js, Jsx, Ts, Tsx</h4><p>I will convert all of the JS code in the project to ES5 so that it can work on most browsers. However, we need a conversion tool called <strong>babel.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VNS0lMj4OvGAiuhctOzTNw.png" /></figure><p>First, I will create a file called .babellrc. You can install many babel plugin types, but in this case, I only installed <strong>@babel/plugin-syntax-dynamic-import </strong>to assist in the file import.</p><p>You can see more at: <a href="https://babeljs.io/docs/en/plugins">https://babeljs.io/docs/en/plugins</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ALAVNTaH8n5XHO10UMKkqg.png" /></figure><p>And this is loader for it. Here, I will compile all js, mjs, jsx, ts, tsx files in the project except the files in node_modules folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YRLP9j_Cqo8lht_wQ8wewA.png" /></figure><h4>b.css</h4><p>You want install <strong>style-loader</strong>, <strong>css-loader.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*hH1HRJxBtct7ncFp8Q8LWQ.png" /></figure><h4>c. image</h4><ul><li>url-loader works like file-loader except that it embeds assets</li><li>smaller than specified limit in bytes as data URLs to avoid requests.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*KHrk6oJ1cd98_tsUwUFD1g.png" /></figure><h4>d. scss</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*yYGsVFF0SPQcwSphp5ESjA.png" /></figure><p><strong>e. Html</strong></p><p>You want to install <strong>html-loader.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*j_iytG9TypSqKn7wJ8OV-w.png" /></figure><p><strong>f. Exception files</strong></p><p>After compile all the files, the remaining files will become ext files to optimize size of the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WTwHLjLuRSKvb2Nh4geCkw.png" /></figure><p>Also, you can refer to more about less, sass, sassModule, media,…</p><h4><strong>In conclusion</strong></h4><p>After that, try running with a terminal: npm run dev. If the result looks like the image below, you have succeeded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5j8QtSfJueVhxt7KH1ptmw.png" /><figcaption>npm run dev</figcaption></figure><blockquote>In the next section, I will introduce to you about plugins, optimization, resolve, …</blockquote><p><strong>References</strong>:</p><ul><li><a href="https://babeljs.io/docs/en/">What is Babel? · Babel</a></li><li><a href="https://webpack.js.org/concepts/">Concepts | webpack</a></li></ul><p><a href="https://medium.com/ag-grid/webpack-tutorial-understanding-how-it-works-f73dfa164f01">https://medium.com/ag-grid/webpack-tutorial-understanding-how-it-works-f73dfa164f01</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e682c00bc0ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[(ReactJS) Understand the nature of Hook in React]]></title>
            <link>https://huynhtrongthoai.medium.com/reactjs-understand-the-nature-of-hook-in-react-8b0d73563e33?source=rss-8fec9e0953a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b0d73563e33</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Thoai Huynh]]></dc:creator>
            <pubDate>Wed, 14 Aug 2019 06:22:26 GMT</pubDate>
            <atom:updated>2019-08-16T16:39:47.332Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*VN9PzFyLOzoMboKy" /></figure><p>Hooks are added to React 16.8 at React conference 2018. Newly added features are great for Stateful Componentsor Stateless Components and it can do everything as same as the<strong> </strong>Stateful Components.Another day, I will have an article analyzing the meaning of these components.</p><p>Back to this article, some people will ask themselves questions about <strong>why should we use Hook? </strong>When we use React Hooks, there will be the following benefits:</p><ol><li>Make components become more compact.</li><li>Allows us to use state within the functional component.</li><li>The bundle size will be greatly reduced by using Hooks. (Because Class inherits from React Component)</li></ol><p>Now, I will briefly summarize how to use some of React Hook’s main functions: useState, useEffect, useRef, useMemo, useCallback.</p><h3><strong>useState</strong></h3><p>useState() is the function that you will use a lot. Instead of using this.state from the Stateful Components<strong>, </strong>you can access the current state with a initial value and can change this state by function.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Feloquent-swirles-u9ypy&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Feloquent-swirles-u9ypy&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fu9ypy%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3c1e4d5c55eee7123f59e1f45c2e40d/href">https://medium.com/media/a3c1e4d5c55eee7123f59e1f45c2e40d/href</a></iframe><h3>useEffect</h3><p>useEffectrelated to side effects and it allows us to make changes to the functional component. Hook has the same effect as ComponentDidMount, ComponentDidUpdate, and ComponentWillUnMount, but is grouped into a single function. useEffect is used to optimize function call and clean up. And it has 2 parameters:</p><ol><li>A anonymous function has no parameters.</li><li>An array contains parameters, the above function is only called when this parameter changes.</li></ol><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fbold-boyd-5jszx&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fbold-boyd-5jszx&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F5jszx%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2aea24df026be18cb999050d2e3b2e5/href">https://medium.com/media/b2aea24df026be18cb999050d2e3b2e5/href</a></iframe><p>For ComponentDidUpdate, it will depend on the second parameter in useEffect. Conversely, if it is an empty array, it will only run once as same as ComponentDidMount</p><p>In addition, no ComponentWillUnMountfunction for functional component. <strong>How to clean up?</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fcodesandbox.io%2Fs%2Frecursing-pine-ycbkl&amp;src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Frecursing-pine-ycbkl&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad60944cc9cfd6cc2c838744fbc733f6/href">https://medium.com/media/ad60944cc9cfd6cc2c838744fbc733f6/href</a></iframe><blockquote>counter unmounted will appear when you navigate to other page.</blockquote><h3>useContext</h3><p>As you know, Redux has a store that stores the entire state of the app. However it is relatively heavy and affects the ability to load bundle files on production environment. Therefore, ReactJS just released useContext to replace Redux.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fmagical-shadow-y1g7z%3Ffontsize%3D14&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fmagical-shadow-y1g7z%3Ffontsize%3D14&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fy1g7z%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/65747909ddf4762bd8a8aa8cfdba99dd/href">https://medium.com/media/65747909ddf4762bd8a8aa8cfdba99dd/href</a></iframe><h3>UseMemo</h3><p>As you know, there are many ways to optimize performance for React applications. You can use <strong>shouldComponentUpdate, PureComponent or memo,… </strong>that helps your app avoid re-render. However, today I will introduce to you about useMemo</p><p>useMemo is a function -&gt; takes a function and an array of dependencies. The input function for useMemo must return a value, and when one of the dependencies changes, useMemo will execute the passed function again.</p><p><strong><em>For Example:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*BLt-r_t4A04nO2TWrFKYFA.png" /><figcaption>useEffect + useState</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*5a28GKJQXLjoV2c4E7Djkw.png" /><figcaption>useMemo</figcaption></figure><p>Lets suppose numberProp is initially 0:</p><ul><li>The useMemo version immediately renders 1.</li><li>The useEffect version renders null, then after the component renders the effect runs, changes the state, and queues up a new render with 1.</li></ul><h3>useCallback</h3><p>useCallback is similar to useMemo. But it returns thefunction callback, not a value. This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.</p><blockquote>useCallback(fn, deps) is equivalent to useMemo(() =&gt; fn, deps).</blockquote><h3>So when should I useMemo and useCallback?</h3><p>Firstly, I will have a example below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*lRA6LH-_LRqc_DJTbO2scw.png" /></figure><p>Make sure you think that it will re-render after name or age updated. However, you have encountered a real trick.</p><p><strong>Explain:</strong> Thanks to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">comparison operators</a> check on options between every render andoptions will be new every time =&gt; it&#39;ll always evaluate to true, meaning the useEffectcallback will be called after every render rather than only when name and agechange.</p><p><strong>Solution:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*nheJBqhdugrC-Owhyi9_xg.png" /></figure><p>Oh, it’s really effective in this case. However, if we think more deeply, name or age is not string, number,… but a function, object, array type. Mean that, name or age will always be evaluate as change :))))</p><p>Therefore, useMemo or useCallbackis generated to solve this situation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*GthitPS5FeKKlIWR7fG1cg.png" /></figure><h3>useRef</h3><p>Now you can use useRef to replace this.myRef = React.createRef () in the component class. useRef is used to access elements inside HTML Node. useRefreturns a ref object and will be kept throughout the life of the component.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fyoung-currying-xy7v4&amp;src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fyoung-currying-xy7v4&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/138f02612670431ae5a63695c75048ab/href">https://medium.com/media/138f02612670431ae5a63695c75048ab/href</a></iframe><h3>Use ESLint Plugin to check for errors</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*LCEMs2Ck_w-kSF9zm55eUQ.png" /><figcaption>Eslint react hook</figcaption></figure><h3>In Conlusion</h3><p>I think Hook is very good but we have to know how to apply it properly. Besides, there are also some less common Hook like: <a href="https://reactjs.org/docs/hooks-reference.html#usereducer">useReducer</a>, <a href="https://reactjs.org/docs/hooks-reference.html#useimperativehandle">useImperativeHandle</a>, <a href="https://reactjs.org/docs/hooks-reference.html#uselayouteffect">useLayoutEffect</a>, <a href="https://reactjs.org/docs/hooks-reference.html#usedebugvalue">useDebugValue</a>.</p><p>And here is a custom hook library that I really like. You can research it through: <a href="https://github.com/streamich/react-use"><strong>https://github.com/streamich/react-use</strong></a></p><p><strong>Reference source: </strong><a href="https://reactjs.org/docs/hooks-intro.html">https://reactjs.org/docs/hooks-intro.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b0d73563e33" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>