Skip to content

@technobuddha > react-hooks > React > Hooks

Function: useDerivedState()

ts
function useDerivedState<T>(initialValue: T | (prevValue: T) => T, deps: readonly unknown[]): [T, Dispatch<SetStateAction<T>>];

Defined in: use-derived-state.ts:32

Like useState, but the value is re-initialized from initialValue whenever deps change. Allows both derived (from dependencies) and manual updates. Useful for state that depends on props or other values, but can also be set directly.

Type Parameters

Type Parameter
T

Parameters

ParameterTypeDescription
initialValueT | (prevValue: T) => TInitial value or function to compute value from previous state.
depsreadonly unknown[]Dependency array; when changed, value is recalculated from initialValue.

Returns

[T, Dispatch<SetStateAction<T>>]

[value, setter] tuple, like useState.

Example

typescript
export function Counter({ start }: { start: number }) {
  // Allow the user to change the counter, but when the start prop changes we always start over.
  const [count, setCount] = useDerivedState(() => start + 1, [start]);

  return (
    <div>
      <div>Count: {count}</div>
      <button onClick={() => setCount(c => c + 1)}>Increment</button>
      <button onClick={() => setCount(() => 0)}>Reset</button>
    </div>
  );
}