U
U
user_of_toster2021-02-03 15:47:14
React
user_of_toster, 2021-02-03 15:47:14

When to use local state and when redux?

1) Is it bad practice to store state that is only used in one component (local) in redux and not in the component itself?
2) Is it bad practice to mix local and redux state?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
N
n1ksON, 2021-02-03
@user_of_toster

1. No
2.
No For example, the display status of a notification does not need to be stored in the store; for this, it is better to use state inside the component.

example - thunk\saga can change a state that is used in only one component outside of the component. You can do this with an action dispatcher. When using a local state, this cannot be done, because the saga cannot get the setState from the component.

It is logical that without redux this cannot be done. After all, the libraries are called: redux -thunk and redux -saga. However, no one bothers you to make API requests directly in the component, but you don’t need to do this. This is considered bad practice.

A
Alexander Aksentiev, 2021-02-03
@Sanasol

It's not clear what the difficulty is.
When this state needs to be used in other places in the application besides this component, especially if these are not parent / child components, then this should be put into the "global" state.
In all other cases, this applies to only one component, why bother with the whole application.
Well, what about mixing completely nonsense, if you have global data that needs to be used somewhere, then how to use it in a component, but do not use any local variables that you need. Where is the logic?

D
Dmitry Makarov, 2021-02-03
@DmitryITWorksMakarov

1. here the key point is not the number of components in which any state is used, but other points. If we store all the states of all components in the editor, then when reading the code, when debugging, there will be a lot of visual noise, it will be difficult to figure out what is happening.
In the editor, we are application data, for example. In the local state, the identifiers of the selected elements in the table.
You can draw a very conditional boundary: what you would store in the database, then we store it in the editor, and the data that we store in private class variables is in the local state. This analogy is closer to me - I started with desktop applications.
But it's all very rough. In a particular situation, it can be anything.
You can come up with and justify a situation where storing the entire state of all components in the redux will be justified.
2. Given the answer to 1, you have to mix.
In general, redux and local state are tools that can be used in a bunch of different ways.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question