React

Global state VS local state 리덕스의 배경이해, 글로벌 변수와 다를 바 없다면 지양되어야 하지 않나?

Asset Type
File Type
When to use
Reference
Created by
Created time
2022/03/13 14:51
Last edited time
2022/03/13 15:58
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.
Some common rules of thumb for determining what kind of data should be put into Redux:
Do other parts of the application care about this data?
Do you need to be able to create further derived data based on this original data?
Is the same data being used to drive multiple components?
Is there value to you in being able to restore this state to a given point in time (ie, time travel debugging)?
Do you want to cache the data (ie, use what's in state if it's already there instead of re-requesting it)?
I've talked to people who chose to put literally everything into Redux. You can do that, and I can understand why you might want to do that, but I personally think that's way too dogmatic.
Part of the issue is that Redux's principle of "a single source of truth" gets over-interpreted to mean that you must put everything in Redux, which isn't the case. It's really more like "a single source of truth, for the data that you decide is worth keeping in Redux".
I think much of the confusion around using Redux is because people don't understand some of the background behind it. I wrote a two-part post, The Tao of Redux, Part 1 - Implementation and Intent and The Tao of Redux, Part 2 - Practice and Philosophy, which tries to explain that background and add context. These two posts look at the history and intent behind Redux's design, how it's meant to be used, why common usage patterns exist, and some of the other ways that you can use Redux.
If anyone's interested, my React/Redux links list has sections on React State Management and Redux Architecture, which point to a lot of additional info on this kind of question.