-
Notifications
You must be signed in to change notification settings - Fork 19
Frontend Application State
There are multiple ways that components can store & access state and the data that they need to perform their functions. While it's tempting to think that there might be a one-size-fits-all approach, each has their own strengths and weaknesses.
The parent/container component maintains state (using this.setState
for classes and the useState
hook for functional components), and passes whatever portions of that are needed as props to their child components. This unidirectional flow is simple and straightforward, but can get cumbersome as the hierarchy grows.
Caseflow uses React Redux to store global application state. This is particularly useful for storing data that needs to be accessed in completely separate parts of the application (such as accessing the currently logged-in user), but accessing it is often more complicated than is needed for most simple uses cases. One should resist using it until placing something in global state seems definitively better than simpler alternatives.
The official Redux site provides a collection of best practices for its usage.
It should be noted that React Redux also now supports the use of hooks for functional components.
More information for Redux can be found in this Wiki within Caseflow.
The Context API is primarily useful when one needs to access a particular set of data from multiple components at different levels within a single hierarchy. Essentially one can establish a state using React.createContext at a particular level (designated by a Context.Provider of the component tree. This shared state can then be accessed by any component nested anywhere below that in the component tree. This is done via use of a Context.Consumer component, or the useContext hook.
This is a good way to share state between multiple components that exist more than one layer apart in the component tree, or between sibling components (which can not pass props to each other). Choose this over using Redux if the stateful data you need to use is not needed at a global/application scale.