Closed devYuraKim closed 2 months ago
isFilled
is a DERIVED STATEokay, so the solution was simpler than I had imagined.
Rather than using state, just set a boolean flag:
isFilled={rating > i}
Mind that the visual change (whether a star is filled or not) is directly derived from the rating state. There’s no need for an additional state variable (isFilled) because you can dynamically calculate if a star should be filled when rendering.
Also, since the UI (stars' filled state) now depends directly on the rating, React will re-render the component immediately after setRating is called, and the stars' appearance will update accordingly.
Because the state updates in React are asynchronous, my isFilled
logic was running before the rating state was actually updated. This is what led to two main problems:
if (i <= rating)
ran. So isFilled
didn’t update properly based on the new rating, leading to the stars not being filled.isFilled
had already been set, the next time the logic ran, it affected all the stars, causing them all to change color.But the logic itself if (i <= rating) setIsFilled(true)
isn't fundamentally incorrect in concept. But I don’t need to store the result in a separate state (isFilled
). Instead, I can derive this value directly from the current rating during rendering.
Star
Component's key value ononClick
eventindex
equal to or greater than 0 and equal to or less than therating
)Star
Component's color ononClick
eventStar
components change color on the second click