This content originally appeared on DEV Community and was authored by S. M. Mahmudur Rahman
Case 1
<i onClick={() => setVisible(!visible)}
className="fi fi-rr-eye absolute top-10 right-3">
</i>
Case 2
<i
onClick={() => setVisible((currentVal) => !currentVal)}
className="fi fi-rr-eye absolute top-10 right-3"
></i>
Both of the provided onClick
handlers in your elements are functionally similar and will work correctly. However, they have slight differences in terms of readability and potential optimizations.
For Case 1:
- This directly toggles the
visible
state using the current value ofvisible
. - If
visible
is managed in a parent component, this can lead to stale closures because thevisible
value might not be the most up-to-date value at the time of execution.
For Case 2:
- This uses the functional form of the state setter, which ensures that the state update is based on the most recent state value, even if the component re-renders before the state is updated.
Recommendation:
The second handler is generally more optimized and is the recommended approach because it leverages the functional update form. This method ensures that you always get the latest state value, avoiding potential issues with stale state closures.
Here's the recommended version:
<i
onClick={() => setVisible((currentVal) => !currentVal)}
className="fi fi-rr-eye absolute top-10 right-3"
></i>
Explanation:
Stale Closures: In the first handler, if the component re-renders between the time the onClick is set up and the time it is executed, the visible value might be outdated, leading to unexpected behavior. The second handler avoids this by using the current state value directly.
Readability: The second handler is more explicit about its intent to toggle the state based on the current state, making the code easier to understand and maintain.
This content originally appeared on DEV Community and was authored by S. M. Mahmudur Rahman
S. M. Mahmudur Rahman | Sciencx (2024-06-18T16:53:47+00:00) Optimized Toggle Visibility. Retrieved from https://www.scien.cx/2024/06/18/optimized-toggle-visibility/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.