Something I learned recently
# useOptimistic
instant feedback while the requests are submitting.
Submit
Request
Respond
Re-render
Submit
Request
Respond
Render
Re-render
# useOptimistic
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
It prevents interface freezing or lag caused by long-running operations.
state changed
Re-render
state changed
Re-render
Re-render
state changed
Slow
state changed
Re-render
X
# PRESENTING CODE
# PRESENTING CODE
# difference
Active decision, control which states are intended to be non-blocking
vs.
Passive, unable to control state but still want non-blocking
# PRESENTING CODE