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
Copy file name to clipboardExpand all lines: react/README.md
+18-8
Original file line number
Diff line number
Diff line change
@@ -787,33 +787,43 @@ Do not directly mutate/update arrays or objects.
787
787
788
788
### 🔷 The new value depends on the old value
789
789
790
-
The state value is not the up-to-date value all the time.
790
+
The state value is not always the up-to-date value.
791
791
792
792
> This is because React batches state updates for performance reasons. So, it doesn't guarantee that the state has been updated immediately after calling `setState`.
793
793
794
-
> If you have a series of state updates happening quickly, like in a loop or due to user interactions, using the regular form may lead to unexpected behavior.
794
+
> This batching mechanism helps reduce the number of re-renders and improves overall performance.
795
+
796
+
> If you have a series of state updates happening quickly, using the regular form may lead to unexpected behavior.
795
797
796
798
- The usual way:
797
799
> ```jsx
798
-
>const [counter, setCounter] =useSate(0);
800
+
>const [counter, setCounter] =useState(0);
799
801
>
800
802
>consthandleClick= () => {
801
803
>setCounter(counter +1);
804
+
>
805
+
>setCounter(counter +1);
802
806
> };
803
807
>```
808
+
>
809
+
> No matter what, this updates the state by `+1` every time you click, not `+2`. In `handleClick`, the `counter` isn't updated immediately, causing both `setCounter` calls to see the same `counter` value.
810
+
>
811
+
> `useState` doesn't trigger a component re-render if it detects that the new value is the same as the old value (applies to primitive values only). Hence, it will re-render the component only once.
804
812
- The guaranteed way:
805
813
> ```jsx
806
-
>const [counter, setCounter] =useSate(0);
814
+
>const [counter, setCounter] =useState(0);
807
815
>
808
816
>consthandleClick= () => {
809
-
>setCounter((currentCounter) => {
810
-
>// `currentCounter` is the most up-to-date version of `counter`.
811
-
>returncurrentCounter+1;
817
+
>setCounter((currVal) => {
818
+
>// `currVal` is the most up-to-date version of `counter`.
819
+
>returncurrVal+1;
812
820
> });
821
+
>
822
+
>setCounter((currVal) => currVal +1);
813
823
> };
814
824
>```
815
825
>
816
-
> Here, you provide a callback function that takes the current state as an argument. React ensures that this callback function is called with the most up-to-date state, even if multiple state updates are queued.
826
+
> Here, you provide a callback function that takes the current state as an argument. React ensures that this callback function is invoked with the most up-to-date state, even if multiple state updates are queued. Consequently, the component will re-render twice.
0 commit comments