<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: anil kumar chaudhary</title>
    <description>The latest articles on DEV Community by anil kumar chaudhary (@simbathesailor).</description>
    <link>https://dev.to/simbathesailor</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F262619%2Fe3350f1f-314c-459d-b2cf-bdcaea273c53.jpeg</url>
      <title>DEV Community: anil kumar chaudhary</title>
      <link>https://dev.to/simbathesailor</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/simbathesailor"/>
    <language>en</language>
    <item>
      <title>useEffectX: A better alternative to useEffect</title>
      <dc:creator>anil kumar chaudhary</dc:creator>
      <pubDate>Sat, 15 Aug 2020 17:01:01 +0000</pubDate>
      <link>https://dev.to/simbathesailor/a-better-alternative-to-useeffect-mn9</link>
      <guid>https://dev.to/simbathesailor/a-better-alternative-to-useeffect-mn9</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--_Qdtpvf1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/0%2ADW2sTbM9H7Eb1iTC" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--_Qdtpvf1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/0%2ADW2sTbM9H7Eb1iTC" alt=""&gt;&lt;/a&gt;Photo by &lt;a href="https://unsplash.com/@avery_james?utm_source=medium&amp;amp;utm_medium=referral"&gt;Avery Morrow&lt;/a&gt; on &lt;a href="https://unsplash.com?utm_source=medium&amp;amp;utm_medium=referral"&gt;Unsplash&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;My experience with &lt;a href="https://reactjs.org/docs/hooks-intro.html"&gt;React hooks&lt;/a&gt; have been amazing. In this article, I will precisely talk on one of the most prominent hooks that we use on a daily basis which is &lt;strong&gt;&lt;em&gt;useEffect.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;I am assuming the readers coming to this article has good understanding on useEffect. If not, please first go through the concept at &lt;a href="https://reactjs.org/docs/hooks-reference.html#useeffect"&gt;reactjs.org&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;So essentially, &lt;strong&gt;&lt;em&gt;useEffect&lt;/em&gt;&lt;/strong&gt; react to changes in dependency list. They have replaced &lt;strong&gt;&lt;em&gt;componentDidMount, componentDidUpdate, componentWillUnmount and componentWillReceiveProps in&lt;/em&gt;&lt;/strong&gt; class based react components.&lt;/p&gt;

&lt;p&gt;It’s very common to react to changes in props values or state values over the lifetime of a component. we also need to compare previous values and current values when reacting to changes often. In the class based component, we had &lt;strong&gt;&lt;em&gt;componentDidUpdate&lt;/em&gt;&lt;/strong&gt; for the similar use-cases.&lt;/p&gt;

&lt;p&gt;It has following interface:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="nx"&gt;componentDidUpdate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;prevProps&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;prevState&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;snapshot&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;You have access to &lt;strong&gt;&lt;em&gt;prevProps(previous props)&lt;/em&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;em&gt;prevState(previous state)&lt;/em&gt;&lt;/strong&gt;, which can be used to make comparisons and react appropriately.&lt;/p&gt;

&lt;p&gt;What about useEffect, how would you do those kind of comparison with them?&lt;/p&gt;
&lt;h3&gt;
  
  
  Solution 1
&lt;/h3&gt;

&lt;p&gt;You can have a &lt;strong&gt;&lt;em&gt;usePrevious&lt;/em&gt;&lt;/strong&gt; custom hook which will always give you the previous value and that you make use in your useEffect to complete the comparison. Let’s see some code.&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://codesandbox.io/embed/keen-lovelace-t27gj"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;Notice, how &lt;strong&gt;&lt;em&gt;usePrevious&lt;/em&gt;&lt;/strong&gt; hook helps us by keeping a track of previous value. Now think about scenario, when there are more than one dependency in our useEffect. We need to make use of &lt;strong&gt;&lt;em&gt;usePrevious&lt;/em&gt;&lt;/strong&gt; hook that many times or we have to re-define our &lt;strong&gt;&lt;em&gt;usePrevious&lt;/em&gt;&lt;/strong&gt; hook to track an array of dependency.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;&lt;em&gt;Isn’t it too much of work every time ?&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Can we have something similar to componentDidUpdate ? We can have previous and current values of the dependencies as the argument of the callback of useEffect.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;That could save us a lot of time while working with update scenarios in useEffect hook.&lt;/p&gt;
&lt;h3&gt;
  
  
  Solution 2
&lt;/h3&gt;

&lt;p&gt;I was able to package everything in a npm package, which can act as a drop in replacement for useEffect anywhere. I call it &lt;strong&gt;&lt;em&gt;useEffectX.&lt;/em&gt;&lt;/strong&gt; Let’s see the the same example we showed in above codesandbox with our shiny new &lt;strong&gt;&lt;em&gt;useEffectX.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://codesandbox.io/embed/ancient-frog-t7tc0"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;Notice now , how we have access to previous values in the arguments of useEffectX’s callback itself. We don’t need any usePrevious hook now plus the arguments are completely optional same with any function. The code snippets below will also work exactly same as official &lt;strong&gt;&lt;em&gt;useEffect&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;useEffectX(() =&amp;gt; {
  console.log(val, someotherVal)
}, [val, someotherVal])

useEffectX(() =&amp;gt; {
 console.log("do something after every render")
})
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;Thanks. Please let me know , what you all think about this &lt;strong&gt;&lt;em&gt;useEffectX.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;


&lt;div class="ltag-github-readme-tag"&gt;
  &lt;div class="readme-overview"&gt;
    &lt;h2&gt;
      &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--vJ70wriM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://practicaldev-herokuapp-com.freetls.fastly.net/assets/github-logo-ba8488d21cd8ee1fee097b8410db9deaa41d0ca30b004c0c63de0a479114156f.svg" alt="GitHub logo"&gt;
      &lt;a href="https://github.com/simbathesailor"&gt;
        simbathesailor
      &lt;/a&gt; / &lt;a href="https://github.com/simbathesailor/use-effect-x"&gt;
        use-effect-x
      &lt;/a&gt;
    &lt;/h2&gt;
    &lt;h3&gt;
      🌟 useEffectX 🌟  : An alternative and drop-in replacement for useEffect which provide previous values of dependency items out of the box.
    &lt;/h3&gt;
  &lt;/div&gt;
  &lt;div class="ltag-github-body"&gt;
    
&lt;div id="readme" class="md"&gt;
&lt;h1&gt;
use-effect-x&lt;/h1&gt;
&lt;h2&gt;
An alternative to useEffect which provide extra info to work with updates&lt;/h2&gt;

&lt;h3&gt;
Why it is needed ?&lt;/h3&gt;
&lt;p&gt;Most of the times we need to respond to updates in our components, where we need to compare previous values and current values. Remember we had the same thing with componentDidUpdate in class based components earlier. useEffect today are not capable to do so out of the box. you need to put in extra effort to get the previous and current values.&lt;/p&gt;
&lt;p&gt;We will focus on the function components now, as they are the most prominent way of developing components today.&lt;/p&gt;
&lt;p&gt;In functional components we typically make use of usePrevious custom hooks. That definetly works. But, you need to do extra work of adding usePrevious hooks for individual items in useEffect dependency.&lt;/p&gt;
&lt;p&gt;What if we have the access of previous and new values in useEffect callback also, so that we dont have…&lt;/p&gt;
&lt;/div&gt;
  &lt;/div&gt;
  &lt;div class="gh-btn-container"&gt;&lt;a class="gh-btn" href="https://github.com/simbathesailor/use-effect-x"&gt;View on GitHub&lt;/a&gt;&lt;/div&gt;
&lt;/div&gt;



&lt;p&gt;&lt;a href="https://twitter.com/simbatheesailor"&gt;https://twitter.com/simbatheesailor&lt;/a&gt;&lt;/p&gt;

</description>
      <category>react</category>
      <category>reacthook</category>
      <category>reactnative</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Useful Patterns with React hooks</title>
      <dc:creator>anil kumar chaudhary</dc:creator>
      <pubDate>Fri, 27 Dec 2019 11:45:02 +0000</pubDate>
      <link>https://dev.to/simbathesailor/recently-wrote-an-article-on-useful-patterns-with-react-hooks-1emg</link>
      <guid>https://dev.to/simbathesailor/recently-wrote-an-article-on-useful-patterns-with-react-hooks-1emg</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--4mxlAron--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/0%2AnJLkAHTH68MGsDbi" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--4mxlAron--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/0%2AnJLkAHTH68MGsDbi" alt=""&gt;&lt;/a&gt;Photo by &lt;a href="https://unsplash.com/@abeso?utm_source=medium&amp;amp;utm_medium=referral"&gt;Sebastian Bednarek&lt;/a&gt; on &lt;a href="https://unsplash.com?utm_source=medium&amp;amp;utm_medium=referral"&gt;Unsplash&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Well, here I am explaining the pattern in React hooks. Who am I ? No body !! Don’t be mad because this is opinionated. Things which worked for me and the people around me.&lt;br&gt;&lt;br&gt;
That’s it.&lt;/p&gt;

&lt;p&gt;First let’s take a step back, and understand what changed with react hooks. Well, A lot has changed but we will talk about those things which are going to be relevant for the the discussion ahead.&lt;/p&gt;

&lt;p&gt;From now on I will be calling React hooks as just hooks. I am tired of adding React in front of every hook word :).&lt;/p&gt;

&lt;p&gt;So the hooks come with a beautiful way of sharing stateful logic between components and also make the reusability of logic much easier. The hooks allows to segregate the logical concerns properly. Remember how we were adding a functionality spread across various lifecycle methods with classes approach.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;It is all good, but problem starts when we think how do we share the logic to other components. we then use to take on HOC patterns and render props pattern, which are very good patterns for sharing the logic. But with all goodness, they also bring lot more not needed verbosity and false hierarchy of our components. It also bring in friction to extract reusable logics.  &lt;/p&gt;

&lt;p&gt;We will not discuss more on class based components. Because I think you are here to see the patterns with hooks and some food for thought.&lt;/p&gt;

&lt;p&gt;Hooks are very good, but there are certain thing which can make situations difficult for even a seasoned developer. One of the problem which I used to encounter is with the custom hooks. A simple custom hooks is quite straight forward to work on. But its start’s getting confusing when it takes multiple arguments.&lt;/p&gt;

&lt;p&gt;Even multiple arguments are good, but when the argument are objects, array or functions , It becomes very difficult to wrap your head around the hook.&lt;br&gt;&lt;br&gt;
Yes, React has provided certain hooks which allows me to mix and match them and solve the issue. I felt myself putting in a lot of focus and head while writing a custom hook which now has started accepting functions. Damn why I have to be so cautious. Why I can’t just pass functions as make it work. Why the infinite loops are getting triggered, why I have to every time think , Should I use useRef or useCallback ? At the time , I would be like&lt;/p&gt;

&lt;p&gt;&lt;a href="https://i.giphy.com/media/UQOjUuqeyIjAzJJ169/source.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/UQOjUuqeyIjAzJJ169/source.gif" alt="Image from giphy"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Yes, but some would say ohh, so you are experienced and you are not able to figure out closures and references. Oh yes my friends, I find myself good with those concepts , but does not like the fact of thinking it every time ,when i am passing references to the hooks. For me custom hooks are just a utility that does processing and return back something which I use in my visual components.&lt;/p&gt;

&lt;p&gt;So some might say, I have not felt that way. I am totally ok with how to write hooks. I would say cool, you have got it. May god teach all of us that finesse.&lt;/p&gt;

&lt;p&gt;But before we see some code, let’s understand why objects, arrays and especially objects are little complicated with hooks.&lt;/p&gt;

&lt;p&gt;My opinion is different for (object, arrays) and different for functions. I would say nothing has changed for objects and arrays as such. If we pass a new reference of arrays or object in class based component, the componentDidUpdate will get triggered. With hooks similarly, a hook with dependencies as arrays or object will rerun and do it’s thing.&lt;/p&gt;

&lt;p&gt;But when it comes to functions we are so used to write them as component instance, that function does not change very often with class based component&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
&lt;br&gt;
Notice above how the Child component (SomeChildComponent) is taking two props:&lt;br&gt;


&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;callback : available on instance, does not change on re-render
callback2: same as above
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;But with hooks, there are no lifecycles now, mental model has changed to an extent.we still write the functions we need to pass on to other hooks or component inside the function. I think that comes natural. It means every time the component re-render the new reference is being passed to the respective hook or components.Btw It has benefits as we are having access to value outside due to closure. Could have been a dragged effort to pull the functions out of the components every time.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;p&gt;Now for simple cases , it’s all ok, but as the logic progresses inside component and the components around it, it demands a lot of focus.&lt;/p&gt;

&lt;p&gt;To the readers who are still with me, let’s see some code and understand various ways of handlings references with hooks. We will go through various cases and by the end we will have correct mental model and patterns to work with hooks. Take all these cases below as some of the ways of working with hooks , not all.&lt;/p&gt;

&lt;p&gt;We will be taking small examples, base code will not change much across cases except certain parts of them. Every example will have base problem and the ways to fix it.&lt;/p&gt;

&lt;h4&gt;
  
  
  &lt;strong&gt;CASE 1:&lt;/strong&gt;
&lt;/h4&gt;

&lt;p&gt;Input&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;&lt;strong&gt;Problem&lt;/strong&gt;  : In above code snippet , we are passing &lt;strong&gt;fn function&lt;/strong&gt; as the argument to useFunctionHook. The &lt;strong&gt;fn&lt;/strong&gt; reference changes on every render of component App. It can cause the effect to re-run again even when it is not desired. Let’s give our first try to fix this issue.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;CASE 1 TRY 1:&lt;/strong&gt;&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Above we moved out the fn definition and now, it will have same reference across re-render. But it’s not always possible to do. We most of the times need access to the local variables available in Components and custom hooks. Following the approach above , will make it difficult to do so.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;CASE 1 TRY 2:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;React also gives us a special hook named as useCallback, which allows us to keep the reference intact based on dependency list passed as the second argument. Here is the API for useCallback&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const fn = useCallback(function() {}, [a, b, c])
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;The first argument function is synchronised with the elements in dependency lists. The fn will only point to a new reference when a, b or c changes in this example. Let’s make use of it to solve our problem.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;p&gt;In the example above, now the fn is again part of the component, but now fn has the access to all the variables inside component due to closures. And also the useFunctionHook makes use of useCallback to persist the reference of fn. In the example the reference of fn will not change across re-render.&lt;/p&gt;

&lt;p&gt;Now lets say the fn access some value from the component something like this:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;But the the fn reference will not change across re-render as the dependency is blank array in our case.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const fnCallback = React.useCallback(fn, [])
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;So in our case , The count referenced by function fn will refer to same initial value across re-render.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The closures created once will persist across re-renders unless the&lt;br&gt;&lt;br&gt;
callback runs again.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Fix is easy, now add count as the dependency for useCallback. For that we must pass countInparent also now to useFunctionHook.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;p&gt;One more alternate adjustment we could have done here is instead of having memoized the callback in useFunctionHook, we could have done it in App component.&lt;/p&gt;

&lt;p&gt;But I think that’s not a good way to go ahead. It’s better if consumer of a custom hook has to do less things to make it work. In our case , we pulled the burden for maintaining the reference to function fn from App component. I think that’s good developer experience.&lt;/p&gt;

&lt;p&gt;On the same lines, some may say useRef is also a viable option here. I would say the typical answer which is it depends. So let’s try the solutions with useRef.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;CASE 1 TRY 3 :&lt;/strong&gt;&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;This approach also work for various scenarios. But there are few things to keep in mind before choosing useRef.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Like useCallback there is no separate dependencies like array, so what could have been achieved with single line may require multiple lines with useRef. we can also write a custom hook like this, which removes some of verbosity from the above code.
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now the above example can be written as :&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;The ref approach becomes silent dependencies. What do I mean by silent dependencies ? . Let’s see that&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;useEffect(() =&amp;gt; {
 // some logic
}, [refDependency, nonRefDependency1, nonRefDependency2])
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;Here above , refDependency will never change after first run. But the values refDependency might be carrying will be updated on every run .&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const { current: updatedValueAlways } = refDependency
//The value updates always but not the ref(refDependency) reference
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;But nonRefDependency1 and nonRefDependency2 are non ref dependency which will change when their respective value changes on re-render.&lt;br&gt;&lt;br&gt;
At times, it becomes impossible to trigger rerun of the effect callback on value change.&lt;br&gt;&lt;br&gt;
So if only refDependency.current changes , it will not trigger the effect callback to run because refDependency itself has not changed.&lt;/p&gt;

&lt;p&gt;Before, we move ahead let’s see one of the pattern that can used for avoiding the more work from consumers of custom hooks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;CASE 2&lt;/strong&gt;&lt;br&gt;&lt;br&gt;
Let’s call it &lt;strong&gt;ref callback pattern&lt;/strong&gt; for now(So this name is pretty common, that I have heard recently, but sounds legit). Now let’s observe the code below:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;PROBLEM:&lt;/strong&gt; In the code above , the App holds the responsibility of passing ref to useFunctionHook. But again as discussed above, we should avoid the effort from the consumer of the hook as much as possible. I think same concept applies for almost every thing in programming. So let’s try to do so.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;CASE 2 TRY 1&lt;/strong&gt; :&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Notice above , how we are using the our callback way of setting up ref. We have also pulled out the responsibility of creating ref from the App component.&lt;br&gt;&lt;br&gt;
Now consumers do not need to worry about creating a ref every time to consume the hook. It would be good if we can extract the functionality of creating callback refs in a common hook. Let’s do that.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Now the code changes to this:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;To summarise the ways we can handle callbacks with react hooks are:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1.&lt;/strong&gt; If possible move out the callback outside the component. This will not be possible almost every time. So mind it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2.&lt;/strong&gt; If the callback is not dependent on any of the values in component scope, then go for useCallback approach or useRef approach with blank dependencies.Remember they become silent in those cases. Can be tricky as the closure created once will not update itself unless it runs again.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3.&lt;/strong&gt; If the callback need to change when certain values changes, go for useCallback approach, passing in desired dependencies.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4.&lt;/strong&gt; Try to minimize the things that consumer of a hook or component have to do to get things working.&lt;/p&gt;

&lt;p&gt;Now we talked about various ways of handling functions with custom hooks. Let’s understand how we are going to handle array and objects with custom hooks.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Notice Type 1 and Type 2 versions of useAcceptOptions hook. Doing the Type 1 will make the the debugging difficult. But the Type 2 can be more deterministic and debugging can be easy. For arrays and objects, nothing has changed. Try to avoid putting dependency like this:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;It’s very common to pass the options inline , so writing like above will run the callback of effect hook to run every time. Try to keep the options as small set of values. Having big objects and array argument to custom hooks becomes difficult to reason later.&lt;br&gt;&lt;br&gt;
Let’s see one more example having functions, object and arrays in it.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;In the example we are just using the knowledge which we have discussed in this article till now. I am not going to explain the code above. I think you should go ahead and read it.&lt;/p&gt;

&lt;p&gt;I think mix of useCallback, useRefValues and useCallbackRef solves almost all of the issues.&lt;/p&gt;

&lt;p&gt;Feel free to point if any issues with the code snippets above. I have also written a handy library to debug hooks. Feel free to try it and let me know. A babel plugin is also available for it.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.npmjs.com/package/@simbathesailor/use-what-changed"&gt;@simbathesailor/use-what-changed&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://twitter.com/simbatheesailor"&gt;Anil Chaudhary&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;As told above, these are my experiences while writing hooks since last year. Please let me know if there are any other good patterns that you guys have been using. &lt;/p&gt;

&lt;p&gt;Thanks&lt;/p&gt;

</description>
      <category>patterns</category>
      <category>reacthook</category>
      <category>usecallback</category>
      <category>useref</category>
    </item>
    <item>
      <title>Debug your Reactjs Hooks with ease !!</title>
      <dc:creator>anil kumar chaudhary</dc:creator>
      <pubDate>Mon, 18 Nov 2019 17:56:01 +0000</pubDate>
      <link>https://dev.to/simbathesailor/debug-your-reactjs-hooks-with-ease-4m28</link>
      <guid>https://dev.to/simbathesailor/debug-your-reactjs-hooks-with-ease-4m28</guid>
      <description>&lt;h3&gt;
  
  
  Debug your Reactjs Hooks with ease !!
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--RCYCAkd4--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/896/1%2A4tJXCyFrW7cFEQNcI5MRhQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--RCYCAkd4--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/896/1%2A4tJXCyFrW7cFEQNcI5MRhQ.png" alt=""&gt;&lt;/a&gt;Sanpshot of debug tool that we are going to achieve&lt;/p&gt;

&lt;p&gt;I have been working on hooks for quite a long time. I use react hooks every day in my open source projects and also at work.&lt;/p&gt;

&lt;p&gt;Now, using useEffect, useCallback, useMemo have really helped me compose the logic well together. But when the dependency list gets long. When I say long , it can be any thing greater than 3 for me and can be more or less for others.&lt;/p&gt;

&lt;p&gt;With these large dependency array, I found it really difficult to debug and find out what is causing my useEffect to run again( same for useCallback and useMemo). I know two strategies to debug:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Break the useEffect logic into multiple useEffect. It is still fine, but expertise and time constraints will vary and might be not the efficient solution at the moment. People will not break the useEffect logic into smaller pieces first, they will first try to spend time using console.log and adding debugger to debug the behaviour. No body want their changes cause any regression by breaking the usEffect logic into multiple useEffects.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;2) Make use of usePrevious hook which can be defined something like this&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;And can be consumed like this:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;&lt;a href="https://gist.github.com/simbathesailor/6defb45314a6015bc1c74a7fb738ba12"&gt;https://gist.github.com/simbathesailor/6defb45314a6015bc1c74a7fb738ba12&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;However we can do it , it quite too much of work every time you run in the issue , where useEffect callback is running unexpectedly.&lt;/p&gt;

&lt;p&gt;To solve the above problem, I tried to create something which can enhance developer experience in this case. Let’s see my try for the above problems.&lt;/p&gt;

&lt;p&gt;I created a simple hook which looks for old value and new values and log it appropriately to help. I have also packaged this simple hook in a npm module.&lt;/p&gt;

&lt;p&gt;The package can also be used with a babel plugin which make it more easy to debug.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Run
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i @simbathesailor/use-what-changed --save-dev
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;ol&gt;
&lt;li&gt;Run
&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i @simbathesailor/babel-plugin-use-what-changed --save-dev
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;Add the plugin entry to your babel configurations&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
 "plugins": ["@simbathesailor/babel-plugin-use-what-changed"]
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;Make sure the comments are enabled for your development build. As the plugin is solely dependent on the comments.&lt;/p&gt;

&lt;p&gt;Now to debug a useEffect, useMemo or useCallback. You can do something like this:&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// uwc-debug
React.useEffect(() =&amp;gt; {
 // console.log("some thing changed , need to figure out")
}, [a, b, c, d]);

// uwc-debug
const d = React.useCallback(() =&amp;gt; {
 // console.log("some thing changed , need to figure out")
}, [a, b, d]);

// uwc-debug
const d = React.useMemo(() =&amp;gt; {
 // console.log("some thing changed , need to figure out")
}, [a]);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;No need to add any import for use-what-changed. Just add a comment //uwc-debug’ above your hooks and you should start seeing use-what-changed debug consoles.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; &lt;em&gt;Frankly speaking the whole package was built, cause I was facing problems with hooks and debugging it was eating up a lot of my time. Now I think I feel quite comfortable with hooks. Now I do not need this often, but i think it can be quite useful for debugging hooks. But this hook helps me to write better hooks almost always.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;I would suggest to use it with the approach above. But for some reason, if you don’t want to go with babel plugin approach. Follow below steps.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;If using npm. Run:
npm i @simbathesailor/use-what-changed --save

If using yarn. Run:
yarn add @simbathesailor/use-what-changed
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;Note: This hook only logs in the development environment. It make use of standard process.env.NODE_ENV to decide. Open devtools console tab to see the logs.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;When only dependency are passed as the single argument&lt;/li&gt;
&lt;/ol&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--RfbCidHC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/908/1%2AhOe9sL-e8BITBQzQysCvxQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--RfbCidHC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/908/1%2AhOe9sL-e8BITBQzQysCvxQ.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Above snapshot show the console log when b and c has changed in the above code example.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Pass two arguments to useWhatChanged which makes it possible for useWhatChanged to log the names of the variables also.&lt;/li&gt;
&lt;/ol&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--0NoYKv7l--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/922/1%2AJyTAodgZ_kY5Mz--0hhNtw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--0NoYKv7l--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/922/1%2AJyTAodgZ_kY5Mz--0hhNtw.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Color coding&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A unique background color will be given to each title text. It helps us in recognising the specific effect when debugging. A unique id is also given to help the debugging further.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--3lXwYxoj--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/916/1%2AXb1zkkAgumOWmPYITIL8rw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--3lXwYxoj--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/916/1%2AXb1zkkAgumOWmPYITIL8rw.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you need to check it live in action and want to play around with it. Go to below codesandbox link&lt;/p&gt;

&lt;p&gt;&lt;iframe src="https://codesandbox.io/embed/nifty-jennings-k2j2f"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;This was my try to solve the problems with reactjs hooks debugging. Hope this helps. Feel free to reach out to me on twitter or github issues for discussions.&lt;/p&gt;

&lt;p&gt;My twitter profile:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://twitter.com/simbatheesailor"&gt;Anil Chaudhary&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;use-what-changed npm package link :&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.npmjs.com/package/@simbathesailor/use-what-changed"&gt;@simbathesailor/use-what-changed&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Thanks everyone !!&lt;/p&gt;

</description>
      <category>reacthook</category>
      <category>consoletable</category>
      <category>javascript</category>
      <category>debugging</category>
    </item>
  </channel>
</rss>
