New Feature: React introduces its new experimental hook — useOptimisitcState()
Tags: typescript, react, hooks, feature
Published: 2023-05-14 23:53:18

React has recently added an experimental hook to the family `useOptimisticState()` that will allow us to manage optimistic state updates in a more functional way.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/urqzc57sf76knh1vqsf6.png)


## Opimistic! What does that mean?
Optimistic state is a technique that allows updating the UI with new data before the data has been fully fetched from the server 🧐
This can help to improve the user experience by making the UI more responsive.

## Assumed syntax:
As we have got used to ReactJs hooks’ syntactical building .. this is a mere assumed syntax for the new hook till we have more information about it.

The useOptimisticState hook, here, will take 2 arguments: a function to fetch the data from the server, and a function to update the UI with the data. The fetch function should return a promise that resolves with the data. The update function should take the data as an argument and update the UI accordingly.

## Example: Hook’s parts ( — The Breakdown)
const [state, setState] = useState(''); 

```
const fetchData = async () => {
  const data = await fetch('https://example.com/data');
  return data.json();
};

const updateUI = (data) => {
  setState(data.name);
};

const [pending, updated] = useOptimisticState(fetchData, updateUI); 

//then use the result in JSX as follows:
{pending && !updated ? "Saving.." : ""}
```

In the previous example, we have 2 normal functions and one magical HOOK:

The fetchData function will fetch the data from the server.
The updateUI function will update the UI with the data.
The useOptimisticState hook will the do the trick.

## What happens behind the scenes? (4 steps — a, b, c, and d)
a. The new hook will call the fetchData function.

b. While at the same time, it will also update the UI accordingly.

The server stays no change and never gets updated with the new data .. However, the UI gets updated 👉 assuming that the data query (POST/PUT/DELETE..etc) will succeed on the server-side (that’s why called optimistic? haa!)

c. If the request to the server is a success ✅ the data gets updated on the server, and here the server is just matching the previously updated UI 🔥 the UI keeps its new state/update (no changes happen on the client-side)

d. While if the fetchData function fails ❌ the hook will roll back the UI to its previous state ⏪

## Do we need That new hook to go Optimistic?
Optimistic State, as stated previously, is a technique used to allow the user interface to respond more effectively, thus improving the user experience.

By the way, It’s all about a matter of choice and the way you choose to go with your application .. and even you can implement the technique by yourself whether by using other tools available in the market or doing manually from scratch .. I mean you do not need useOptimisticState() hook to implement the optimistic effect in our applications.

Of those tools that have been around for a while: _[Quick Examples]_

Use a **library** like `react-query` or `swr`:
These libraries provide a number of features for managing asynchronous requests, including optimistic state.
Use a **custom** hook.
A custom hook is a function that takes some state and returns a new state by creating a hook that takes the current state and the response from the server, and returns a new state.
You can also manage optimistic state **manually**.
To do this, you will need to keep track of the current state of the application, and update the state based on the response from the server.
Here’s an example on how to implement optimistic state update with a fake server:

{% embed https://codesandbox.io/embed/tutorial-optimisticstate-simulating-optimistic-state-updates-in-react-ldvkwf?fontsize=14&hidenavigation=1&theme=dark %}