You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
> This effect is going to fire after every render. If we only want the interval to be set up once on initial render (i.e similar to componentDidMount), we simply pass an empty array
789
+
( i.e [] ) as the dependency list.
790
+
791
+
> If we now take a look at the browser, we can see that the class counter is working as expected but the hook counter is displaying the value of `1` and not incrementing every second.
792
+
> In our mind, the problem statement is simple. Create an interval once and destroy it once.
793
+
794
+
> The empty depndency list ensures that the timer is set only once and return function to destroy the timer that we've created. Why then our counter doesn't work as expected ?
795
+
796
+
REMEMBER -->
779
797
If you think dependency array is a way to specify when you want to rerun the effect, you are going to run into problems.
780
798
781
799
Instead, dependency array should be thought of as a way to let react know about everything that the effect
Therefore, the problem is --> By specifying an empty array, we've basically told React to ignore watching for changes in the count variable.
803
+
So, React goes like -> On initial render, the count value is 0 which implies setCount will set it to 0 + 1 = 1 and that'll be rendered in the
804
+
browser. Now because the dependency array is set to [], we're telling React that it doesn't have to watch for changes in the count value. Count
805
+
value is equal to 1 right now and React will just render that value through the different re-render cycles. If we want React (i.e the `useEffect` hook)
806
+
to keep an eye on a variable, we just have to add it to the dependency array (i.e [count]). And our problem will be solved.
807
+
808
+
BTW, for this example there is another way to get it working without the dependency list. In the tick function, we use the second form of setCount.
809
+
We get access to previous count and we set previous count + 1. (Read this to understand more --> https://react.dev/reference/react/useState#updating-state-based-on-the-previous-state)
810
+
811
+
Now since setCount keeps track of the previous count value, we don't have to specify count as a dependency and that array can again be set to [].
0 commit comments