{React}

Something I learned recently

  1. useOptimistic (19)
  2. useTransition (18)
  3. useDeferredValue (18)

Agenda

# useOptimistic

What is Optimistic Update

instant feedback while the requests are submitting.

Submit

Request

Respond

Re-render

Submit

Request

Respond

Render

Optimistic

General

Re-render

# useOptimistic

Scenarios

Let's take a look!!!

















  const [todos, setTodos] = useState([ {title:'Do Laundry', checked:true} ]);
  const [optimisticTodos, addOptimisticTodo] = useOptimistic(a,b)






      {todos.map(todo => (
        <TodoItem title={todo.title} checked={todo.checked} />
      ))}











      {optimisticTodos.map(todo => (
        <TodoItem title={todo.title} checked={todo.checked} sending={todo.sending} />
      ))}












  const [todos, setTodos] = useState([ {title:'Do Laundry', checked:true} ]);
  const [optimisticTodos, addOptimisticTodo] = useOptimistic(a,b)
  const [optimisticTodos, addOptimisticTodo] = useOptimistic(todos,b)
  
  
  
  
  
  
  
   
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  // updateFn nextTodo is the optimisticValue which will be sent to BE
  const updateFn = (currentTodos, nextTodo) => { //
      // currentTodos was the previous state from useState
      return [...currentTodos, {title: nextTodo, checked:false, sending:true}]
  }  
  
  
  
  
  
  
  const [todos, setTodos] = useState([ {title:'Do Laundry', checked:true} ]);
  const [optimisticTodos, addOptimisticTodo] = useOptimistic(todos,updateFn)
   
       {optimisticTodos.map(todo => (
        <TodoItem title={todo.title} checked={todo.checked} sending={todo.sending} />
      ))}
 
  
  
  
  



  async function formAction(formData) {
    let newTodo = formData.get("todo")
    addOptimisticTodos(newTodo);
    form.current.reset();
    let response = await createTodo(newTodo);
    setTodos([...todos, {title: response.title, checked:false, sending:false}]) 
     // 或者可以不加 sending
  }

  
  
  
  
  
  
  
  
  
  
  

  
  
# PRESENTING CODE
# useTransition

What is non-blocking UI 

It prevents interface freezing or lag caused by long-running operations.

state changed

Re-render

state changed

Concurrent Transition

General

Re-render

Re-render

state changed

Slow

state changed

Re-render

X

Some Demo

# PRESENTING CODE

Some Demo

# PRESENTING CODE
# difference

useTransition

vs
useDeferredValue

Active decision, control which states are intended to be non-blocking
vs.
Passive, unable to control state but still want non-blocking

Reference

# PRESENTING CODE

Code

By 陳Ken

Code

  • 87