[SOLVED] store data outside of a react component and derive state from it

Issue

This Content is from Stack Overflow. Question asked by Maddin

Is it legit to store data outside of a react component and change it from inside the component and derive state from it? This could help when updating complex deep-nested states.

import React from "react";

let globalState = {
  foo: { bar: { baz: { value: 0 } } },
};

const Component = () => {
  const [state, setState] = React.useState(globalState);
  let baz = globalState.foo.bar.baz;

  const changeValue = () => {
    baz.value += 1;
    setState({ ...globalState });
  };

  return (
    <div>
      <label>{state.foo.bar.baz.value}</label>
      <button onClick={changeValue}>change</button>
    </div>
  );
};



Solution

This sounds like something that would ideally be handled with the use of Context.
Using context can help you manage the state globally rather than mutating objects and passing them up and down the tree all the time, making them difficult to manage.


This Question was asked in StackOverflow by Maddin and Answered by richtea It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?