R
R
Ruslan2019-09-27 19:15:06
React
Ruslan, 2019-09-27 19:15:06

When not to use vuex | redux | flux?

Hello!
The question arose whether or not to use state management libraries at the level of the entire application.
Scenarios for working with data in applications (spa or web?) can be different, but I conditionally divided them into 2:
First : we have some small amount of data that is completely loaded into the application, and we can save it in a shared storage. At the same time, if we open different pages on which we need to display different filtered data, then we use functions that pull what we need from the downloaded data, and when we change something, we update them centrally through the storage functions (and also sent to the server).
Second: we have a lot of data (millions of objects on the server), and we do not download them all, but make a request that returns a maximum of several dozen objects. So the question is: is it necessary in this case to put them in the repository and work with them through the repository. This is the point that confuses me: the user can simultaneously open two components that need different data sets from the server , and we have only one in the storage, isn’t it better every time the next page is opened, in the component that displays the list, request data from the server?
Here's what makes it even more difficult to think: if we use vue or react, then we have an application - SPA, even if the user opens it in a browser. And if our application provides that only one instance of the list with our objects can be opened at a time, then we can use the state store and update it from the server every time the user changes the filters. And if the user opens different pages of this application in different browser tabs, then, in fact, these will be different instances of the application, each of which will have its own state. Is it logical?
Still, the question is: in what cases is it necessary to store data from the server in the state store (vuex | redux), and in what cases it is not?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
V
Vlad_Murashchenko, 2019-09-28
@Vlad_Murashchenko

Everything is simple.
1) the state is relative to some particular component that is itself responsible for CRUD with the given state - use local state.
Example: a list of some elements, we don’t want to display or work with an element from this list somewhere in another part of the application, this is some kind of nonsense, although designers can come up with all sorts. And if they come up with something, they will have to raise this state higher or take it to the global one.
2) if the state is used in different components that are not directly related to each other, then it is more convenient to use the global state to conveniently inject it into the necessary components and provide them with an interface for working with it.
Example: the server provides us with a user object in which there is a status, name, photo, some other data. The status is displayed and edited in one component, the name with a photo is displayed in another, and edited in some completely separate form with its own state. Here we would have to keep this state somewhere very high and far from the components that control it, the global state makes it easier to work with similar states

R
Robur, 2019-09-28
@Robur

See how GraphQL + Apollo client works. Pay special attention to normalization and caching on the client. There, people have already thought very seriously about the problems that you have voiced (and others too) and have come up with a lot of good things - they will not take advantage of sin. If not by the technologies themselves, then by the approaches and solutions.

A
Andrey K, 2019-09-28
@kuftachev

Компонент загружает данные с сервера, которые ему нужны, потом он с ними работает и из стирает сборщик мусора.
Хранилища нужны для отслеживания общего состояния приложения (или модуля), то есть, если это обычный CRUD, то далеко не факт, что есть смысл этим данные хранить в общем состоянии.
И не нужно путать с кешированием, так как это разные задачи.

J
Jhn Doe from by, 2019-09-28
@spbislanders

если мы пользуемся vue или react, то у нас приложение – SPA, даже если пользователь его открывает в браузере.

вы точно понимаете что такое spa? мне ничего не мешает юзать vue или react вне spa
логично, где вопрос?
а) данные нужно пробросить из одного компонента в другой, не имея при этом связанно цепочки, либо она слишком длинная, данные пробрасываются, чтобы обновить локал стор какого-то компонента
б) хочу настроить серверный рендер шаблонов с какими-то динамическими данными(из БД). Там как раз и используется global store для этого
5млн объектов из базы в глобал сторе? НЕТ
первые 20-30 можно поместить, далее пробросить их компонентам страницы
следующие 4.9млн загружать в локал стор, все.
не понял вопроса, кони-люди смешалось вообще все...
2 компонента на странице. Каждому нужны данные с разных ресурсов?
ну дак и загружайте их в локал сторы этих компонентов. Запрашивайте данные с сервера, в чем проблема?
global store (vuex, redux) может хранить одновременно хоть сотню наборов
И да читайте документацию по redux, там это все есть

I
Ivan Driuk, 2019-09-29
@IDriuk

Если данные обновляются с сервера без перезагрузки страницы, то всегда хранить в редакс. Миллионы значений за раз не загружать )). Если разным компонентам нужны разные данные, то получаем их в стейт редакса, а уже оттуда коннектить к компонентам. Итого, редакс не использовать тогда, когда вся логика и работа с данными на бекенде. Или когда хочется усложнить себе жизнь обрабатывая/сохраняя логику и данные внутри компонентов.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question