Course contentsShow
← React
Lesson 1722 of 2,39641. State Management EcosystemFree lesson

useAtomValue and useSetAtom for Optimization

Split hooks that only subscribe to reads or only provide setters to avoid unnecessary re-renders.

useAtomValue and useSetAtom for Optimization

What You'll Learn

You'll discover how to split Jotai's useAtom into read-only and write-only hooks to prevent unnecessary component re-renders.

The Performance Problem with useAtom

When you call useAtom(myAtom), you get both the value and the setter function:

const [count, setCount] = useAtom(countAtom);

The catch: This component now re-renders every time count changes, even if the component only uses setCount!

The Solution: Split Your Concerns

Jotai provides two specialized hooks:

useAtomValue: Read-Only Subscription

import { useAtomValue } from 'jotai';

function DisplayCount() {
  const count = useAtomValue(countAtom);
  // This component re-renders when count changes
  return <div>Count: {count}</div>;
}

This component subscribes to changes and re-renders when the atom updates.

useSetAtom: Write-Only, No Subscription

import { useSetAtom } from 'jotai';

function IncrementButton() {
  const setCount = useSetAtom(countAtom);
  // This component NEVER re-renders when count changes!
  return <button onClick={() => setCount(c => c + 1)}>+1</button>;
}

This component gets the setter but doesn't subscribe to value changes—no re-renders when the count updates.

The Analogy

Think of useAtom as subscribing to a newsletter and getting an editor's email. useAtomValue is just subscribing (you get updates). useSetAtom is just getting the editor's email (you can send changes but don't receive updates).

When to Use What

  • useAtomValue: Display components, computed values, anything that reads
  • useSetAtom: Form handlers, event callbacks, anything that only writes
  • useAtom: Components that genuinely need both (less common than you think!)

Key Takeaway: Split useAtom into useAtomValue and useSetAtom to optimize by having components only re-render when they actually need the atom's value, not just its setter.