useRafState

Tags:

A React Hook that uses requestAnimationFrame to update the state in the next frame for better performance. This Hook works similarly to React.useState, except for the timing of updates.

Scenarios

  • Animation Scenario Optimization: Used to improve performance in animations or frame rendering, updating the state only in the next frame
  • High-frequency Event Handling: For example, reducing the state update frequency during scrolling or dragging to prevent performance degradation
  • ...

Demo

Source
Count:
0

Usage

// Use in scenarios where performance optimization is needed const [state, setState] = useRafState({ isScrolling: false }) // You can use the `deep` option inherited from `useSafeState` to further reduce rendering and thus optimize performance const [{ x, y }, setPosition] = useRafState({ x: 0, y: 0 }, { deep: true })

Source

Click links below to view source on GitHub.

API

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

Initial State

Same as React.useState.

Options

For more details, refer to useSafeState#options.

Returns

Same as React.useState.