React: useOptimistic
Problem: Let's say we have a "๐๐ผ" button. When the user clicks on it, API call is made to save the value in the backend A message "Liked" is displayed if the save was successful But if the API call takes 5 seconds for the response, the UI looks laggy. Solution: useOptimistic hook: "Give me a temporary override of baseState while a transition is pending." Note: It does NOT store an independent state. It derives its value from the “base” (real) state. Rules: useOptimistic requires that there is some state that goes to ‘pending’ immediately after setting optimistic value There are several ways to make the component go to ‘pending’ like using startTransition When the pending transition stops, React stops using the optimistic value and re-renders using the real state value that your code updated. Lifecycle ๐๐ผclicked -> transition starts -> optimistic value used -> component in "pending" state -> API returns (component is no more in...