Skip to main content
usePreviousValue
@coinbase/cds-common@8.13.6
Returns the previous value of a given variable, useful for comparing current and previous states in effects or for tracking changes over time.
Import
import { usePreviousValue } from '@coinbase/cds-common/hooks/usePreviousValue'
SourceView source code

Basic usage

Loading...
Live Code
function Example() {
  const [count, setCount] = useState(0);
  const previousCount = usePreviousValue(count);

  return (
    <VStack gap={3} alignItems="start">
      <VStack gap={1}>
        <TextHeadline>Current count: {count}</TextHeadline>
        <TextHeadline>Previous count: {previousCount ?? 'None'}</TextHeadline>
      </VStack>
      <Button onClick={() => setCount(count + 1)}>Increment</Button>
    </VStack>
  );
}

With Complex Values

Loading...
Live Code
function Example() {
  const [user, setUser] = useState({ name: 'John', age: 25 });
  const previousUser = usePreviousValue(user);

  const updateAge = () => {
    setUser((prev) => ({ ...prev, age: prev.age + 1 }));
  };

  return (
    <VStack gap={3} alignItems="start">
      <VStack gap={1}>
        <TextHeadline>Name: {user.name}</TextHeadline>
        <TextHeadline>Age: {user.age}</TextHeadline>
        <TextHeadline>Previous age: {previousUser?.age ?? 'None'}</TextHeadline>
      </VStack>
      <Button onClick={updateAge}>Add Year</Button>
    </VStack>
  );
}

Is this page useful?

Coinbase Design is an open-source, adaptable system of guidelines, components, and tools that aid the best practices of user interface design for crypto products.