useSafeState

Tags:

A React Hook similar to React.useState, but suppresses false warning reports in React <= 17 and includes an optional deep comparison feature (deep, default is false). It is designed as a safe and efficient alternative to React.useState.

For a detailed explanation of the advantages of useSafeState, see Safe State.

Scenes

  • State Management: Used as a replacement for React.useState, to avoid false warning reports in React <= 17.
  • Performance Optimization: Avoids unnecessary re-renders by deeply comparing new and old states (deep option, off by default).

Demo

Source
Basic State:
Hello
Shallow Object State:
Hooks
Deep Object State:
Hooks

Usage

const [info, setInfo] = useSafeState({ name: 'Bob' }, { deep: true })

setInfo({ name: 'Amy' }) // Setting a new value will trigger a re-render
setInfo({ name: 'Amy' }) // Setting the "same" value again will not trigger a re-render when the deep option is enabled

Source

Click links below to view source on GitHub.

API

const [state, setState] = useSafeState(initialState, options)

InitialState

The initial value of the state, the same as React.useState.

Options

export type UseSafeStateOptions = {
  /**
   * Deeply compares the new state with the old one before updating.
   * 
   * The state is only updated when the new state is "different" from the old one, to reduce unnecessary re-renders.
   *
   * @defaultValue false
   */
  deep?: boolean
}

Returns

The same as React.useState.