Skip to content

Dependency-based reinitialization of useState #14738

@jonrimmer

Description

@jonrimmer

Do you want to request a feature or report a bug?

Feature

What is the current behavior?

Consider I want to have a dynamically calculated list of options, and a piece of state that represents the currently selected option. I can achieve this using hooks as follows:

const options = useMemo(() => {
  // Calculate the options
}, [dep1, dep2]);

const [choice, setChoice] = useState(options[0]);

const result = useMemo(() => {
  // Calculate the displayed result
}, [choice]);

However, a problem occurs if either dep1 or dep2 changes. The list of options changes, which means choice may no longer be valid. To fix this, I must split choice into a selected value and a memoized value that checks for validity:

const [selectedChoice, setSelectedChoice] = useState(options[0]);

const choice = useMemo(() => {
  if (options.includes(selectedChoice) {
    return selectedChoice;
  } else {
    setSelectedChoice(options[0]);
    return options[0];
  }
}, [options, selectedChoice]);

What is the expected behavior?

It would useful if we could declare dependencies for useState, in the same way that we can for useMemo, and have the state reset back to the initial state if they change:

const [choice, setChoice] = useState(options[0], [options]);

In order to allow preserving the current value if its valid, React could supply prevState to the initial state factory function, if any exists, e.g.

const [choice, setChoice] = useState(prevState => {
  if (prevState && options.includes(prevState) {
    return prevState;
 else {
    return options[0];
 }
}, [options]);

Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?

16.8.0-alpha.1

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions