useOptimistic

useOptimistic은 UI를 낙관적으로 업데이트할 수 있게 해주는 React Hook입니다.

const [optimisticState, setOptimistic] = useOptimistic(value, reducer?);

레퍼런스

useOptimistic(value, reducer?)

useOptimistic은 React Hook으로, 비동기 작업이 진행 중일 때 다른 상태를 보여줄 수 있게 해줍니다. 인자로 주어진 일부 상태를 받아, 네트워크 요청과 같은 비동기 작업 기간 동안 달라질 수 있는 그 상태의 복사본을 반환합니다. 현재 상태와 작업의 입력을 취하는 함수를 제공하고, 작업이 대기 중일 때 사용할 낙관적인 상태를 반환합니다.

이 상태는 “낙관적” 상태라고 불리는데, 실제로 작업을 완료하는 데 시간이 걸리더라도 사용자에게 즉시 작업의 결과를 표시하기 위해 일반적으로 사용됩니다.

import { useOptimistic } from 'react';

function MyComponent({name, todos}) {
const [optimisticAge, setOptimisticAge] = useOptimistic(28);
const [optimisticName, setOptimisticName] = useOptimistic(name);
const [optimisticTodos, setOptimisticTodos] = useOptimistic(todos, todoReducer);
// ...
}

아래에 더 많은 예시를 참조하세요.

매개변수

  • state: 작업이 대기 중이지 않을 때 초기에 반환될 값입니다.
  • updateFn(currentState, optimisticValue): 현재 state와 addOptimistic에 전달된 낙관적인 값을 취하는 함수로, 결과적인 낙관적인 state를 반환합니다. 순수 함수여야 합니다. updateFn은 두 개의 매개변수를 취합니다. currentStateoptimisticValue. 반환 값은 currentStateoptimisticValue의 병합된 값입니다.

반환값

  • optimisticState: 결과적인 낙관적인 상태입니다. 작업이 대기 중이지 않을 때는 state와 동일하며, 그렇지 않은 경우 updateFn에서 반환된 값과 동일합니다.
  • addOptimistic: addOptimistic는 낙관적인 업데이트가 있을 때 호출하는 dispatch 함수입니다. 어떠한 타입의 optimisticValue라는 하나의 인자를 취하며, stateoptimisticValueupdateFn을 호출합니다.

set functions, like setOptimistic(optimisticState)

The set function returned by useOptimistic lets you update the state for the duration of an Action. You can pass the next state directly, or a function that calculates it from the previous state:

const [optimisticLike, setOptimisticLike] = useOptimistic(false);
const [optimisticSubs, setOptimisticSubs] = useOptimistic(subs);

function handleClick() {
startTransition(async () => {
setOptimisticLike(true);
setOptimisticSubs(a => a + 1);
await saveChanges();
});
}

Parameters

  • optimisticState: The value that you want the optimistic state to be during an Action. If you provided a reducer to useOptimistic, this value will be passed as the second argument to your reducer. It can be a value of any type.
    • If you pass a function as optimisticState, it will be treated as an updater function. It must be pure, should take the pending state as its only argument, and should return the next optimistic state. React will put your updater function in a queue and re-render your component. During the next render, React will calculate the next state by applying the queued updaters to the previous state similar to useState updaters.

Returns

set functions do not have a return value.

Caveats

  • The set function must be called inside an Action. If you call the setter outside an Action, React will show a warning and the optimistic state will briefly render.
자세히 살펴보기

How optimistic state works

useOptimistic lets you show a temporary value while an Action is in progress:

const [value, setValue] = useState('a');
const [optimistic, setOptimistic] = useOptimistic(value);

startTransition(async () => {
setOptimistic('b');
const newValue = await saveChanges('b');
setValue(newValue);
});

When the setter is called inside an Action, useOptimistic will trigger a re-render to show that state while the Action is in progress. Otherwise, the value passed to useOptimistic is returned.

This state is called the “optimistic” because it is used to immediately present the user with the result of performing an Action, even though the Action actually takes time to complete.

How the update flows

  1. Update immediately: When setOptimistic('b') is called, React immediately renders with 'b'.

  2. (Optional) await in Action: If you await in the Action, React continues showing 'b'.

  3. Transition scheduled: setValue(newValue) schedules an update to the real state.

  4. (Optional) wait for Suspense: If newValue suspends, React continues showing 'b'.

  5. Single render commit: Finally, the newValue commits for value and optimistic.

There’s no extra render to “clear” the optimistic state. The optimistic and real state converge in the same render when the Transition completes.

중요합니다!

Optimistic state is temporary

Optimistic state only renders while an Action is in progress, otherwise value is rendered.

If saveChanges returned 'c', then both value and optimistic will be 'c', not 'b'.

How the final state is determined

The value argument to