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

Viewed 57

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>
  );
};

Update:

My main intention of this aproach is to get a cleaner way of updating nested state properties. In my current component I use immer-produce to update nested values of the state, but even with produce it becomes extremely nasty when coming to nested state with arrays, indices etc.

This is an actual code snippet from my application:

const changeAction = useCallback((newAttrs) => {
  setState(
    produce((draft) => {
      draft.newOrders[draft.selectedOrderIndex].nodes[
        draft.selectedNodeIndex
      ].actions[draft.selectedActionIndex] = {
        ...draft.newOrders[draft.selectedOrderIndex].nodes[draft.selectedNodeIndex]
          .actions[draft.selectedActionIndex],
        ...newAttrs,
      };
    })
  );
}, [setState]);

Is there any other aproach to clean this up?

1 Answers

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.

Related