DEV Community

Discussion on: ES6 Generators for State Management in React

Collapse
 
rjerue profile image
Ryan Jerue

Thank you for the post, there's not a ton of talk on using iterators with react state and they have a great potential to create state machines. Why put the iterator into the static context? While this works well for global state management, wouldn't this break down once you rendered two different instances of the same component?

Why not something along the lines of:

function Fun() {
  const [colorIterator, setColorIterator] = useState(createColorIterator());
  const [colorState, setColorState] = React.useState(colorIterator.next().value);

  function updateBackgroundColor() {
    setColorState(colors.next().value);
  }

  function reset() {
    setColorIterator(createColorIterator());
  }

  const { value, done } = colorState;

  return (
    <Container backgroundColor={value}>
      <h1>Hello!</h1>
      <Button disabled={done} onClick={updateBackgroundColor}>
        Change background color
      </Button>
      <Button onClick={reset}>Reset</Button>
    </Container>
  );
}
Enter fullscreen mode Exit fullscreen mode

The fear that I have with the above implementation is that the iterator is in state... and it's getting mutated! Which is bad!

That being said, it does "work." Is there a better pattern or lib out there that could avoid mutating a value in state?