DEV Community

S. M.  Mahmudur Rahman
S. M. Mahmudur Rahman

Posted on

Optimized Toggle Visibility

Image description

Case 1

<i onClick={() => setVisible(!visible)} 
className="fi fi-rr-eye absolute top-10 right-3">
</i>
Enter fullscreen mode Exit fullscreen mode

Case 2

<i
onClick={() => setVisible((currentVal) => !currentVal)}
className="fi fi-rr-eye absolute top-10 right-3"
></i>
Enter fullscreen mode Exit fullscreen mode

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 visiblestate using the current value of visible.
  • If visibleis managed in a parent component, this can lead to stale closures because the visiblevalue 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>
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)