useSetState

Tags:

A React Hook that uses the React Class Component's this.setState method for state management.

Scenes

  • Closer to Developer Habits: Similar to the this.setState in Class Components, more aligned with developers' previous habits
  • State Management Scenes: Implements incremental updates to the component's state without needing to replace the entire state object
  • Form Handling Scenes: Manages the state of form items, supports updates to specific fields, facilitating the implementation of complex form logic
  • ...

Demo

Source

Usage

const [info, setInfo] = useSetState({ name: 'Bob', age: 18 }, { deep: true }) setInfo({ name: 'Amy' }) // Set new value, only updates the name field, the age field remains unchanged setInfo({ age: 20 }) // Set new value, only updates the age field, the name field remains unchanged setInfo({ name: 'Amy' }) // Setting the 'same' value again will not trigger a re-render. Reference to options in useSafeState.

Source

Click links below to view source on GitHub.

API

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

Initial State

The same as React.useState.

Options

For more details, refer to useSafeState#options.

Returns

The same as React.useState.