Dealing with local state in react and redux

后端 未结 3 1923
时光说笑
时光说笑 2021-02-02 10:01

Is it OK to store local state in the state object when using react together with redux? Storing everything in the state tree via actions quickly becomes tedious. It

相关标签:
3条回答
  • 2021-02-02 10:41

    This is difficult to answer, because different people will classify different parts of a component as "state".

    Since Redux is concerned with application state, as a rule of thumb, anything you would expect an application level "undo/redo" button to effect should happen as a Redux Action. The fact that Redux has an undo store plugin is possible only because of the reach of application state.

    Certainly some animations would not be undoable, since these should really be connected to changes in the app state, not changes in-and-of themselves. The rest of your examples, though, sound very much like app state. If I sorted a table, and then pressed undo, I would absolutely expect the sorting to be undone.

    0 讨论(0)
  • 2021-02-02 10:55

    As Tyrsius already mentioned - there are different opinions about this.

    For us - as a rule of thumb - we make sure to track everything with the application state which we would like to be able to see if we'd connect to some users current session remotely.

    If we don't care to see whether the mouse is hovered over some element, we might only use the components state for this (if we need the state then at all).

    We have only a few such cases in our scripts though, since we'd like to know exactly what the user sees in most cases for easier debugging.

    You're mentioning expanded/collapsed states for panels - we sometimes create components which handle this expanded/collapsed logic for us, so we don't have to write such reducers all the time for every panel we create.

    We can use these components like this:

    <Panel id="somePanelId">some content</Panel>
    

    The panel component will make sure to track the panels active state within the application state. This way it's really easy to keep your code simple and not let it explode.

    0 讨论(0)
  • 2021-02-02 10:59

    This is now answered in the redux FAQs:

    There is no “right” answer for this. Some users prefer to keep every single piece of data in Redux, to maintain a fully serializable and controlled version of their application at all times. Others prefer to keep non-critical or UI state, such as “is this dropdown currently open”, inside a component's internal state.

    Using local component state is fine. As a developer, it is your job to determine what kinds of state make up your application, and where each piece of state should live. Find a balance that works for you, and go with it.

    0 讨论(0)
提交回复
热议问题