useTransition vs useDeferredValue

ZainDev
2 min readAug 20, 2023

--

The difference between useTransition and useDeferredValue hooks, along with some examples:

  • useTransition is a hook that allows you to defer the rendering of a state update until the current transition has completed. This can be useful for improving the performance of your application by preventing unnecessary re-renders.
  • useDeferredValue is a hook that allows you to wrap a value and defer its rendering until the current transition has completed. This can be useful for improving the performance of your application by preventing unnecessary re-renders of components that depend on the value.
const [count, setCount] = useState(0);

const { isPending, startTransition } = useTransition();

const incrementCount = () => {
startTransition(() => {
setCount(count + 1);
});
};

return (
<button onClick={incrementCount}>
Increment Count
</button>
);

In this example, the incrementCount function uses the startTransition function to defer the rendering of the setCount function until the current transition has completed. This means that the count state variable will not be updated until the user has finished clicking the button.

const value = useDeferredValue(() => {
return fetch("/api/value").then((response) => response.json());
});

const renderValue = () => {
return <div>The value is {value}</div>;
};

return (
<div>
<button onClick={() => value.refresh()}>Refresh Value</button>
<renderValue />
</div>
);

In this example, the value variable is wrapped in the useDeferredValue hook. This means that the value of the value variable will not be rendered until the current transition has completed. The refreshValue function uses the refresh() function to trigger a new transition, which will cause the value variable to be re-rendered.

I hope this explanation was helpful. Please let me know if you have any other questions.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

ZainDev
ZainDev

Written by ZainDev

Software Engineer - Senior Full Stack Developer (Tech and Project Lead) ✓Angular ✓React ✓Next ✓Node ✓WebSocket ✓JavaScript ✓TypeScript

No responses yet

Write a response