When To Store And When To State

Krae Wind
2 min readAug 11, 2021

--

When first learning the frontend JavaScript framework, React, it can be noticeably daunting to know when to create a local state for a particular component or use a parent component’s local state with props and callbacks.

Throw in Redux’s store and the placement of data might as well be guesswork for the nubile developer. This blog post aims to clear up some of the doubt on when to use which form of storage.

The big picture is this: Redux’s store is used for data that needs to be used across multiple, often unrelated, components. For example if in my Activities and Values app, a value changes and that shifts the score and ranking of an activity, it would be an absolute nightmare to pass the info up one component at a time until it reached a common parent, and then back down again until it reached the proper component.

Local state is used more for components where the state stored in that component is only being accessed by itself or a child and MAYBE a grandchild.

A couple things to keep in mind…

ANYTIME a component’s state or Redux’s store is updated, any component associated with the changing data will likely RE-RENDER. This took some getting used to on my part as I got caught in an infinite loop of re-rendering if my render function in class components fetched or manipulated data in anyway. (By the way, to fix this, I used componentDidMount and componentDidUpdate lifecycle methods to make a distinction whereas render is ALWAYS run)

Although it may seem easier to just connect everything to the store, it will inevitably cause too much re-rendering and a performance hit when/if you scale up.

Lastly, remember to never alter state directly. Use only approved methods such as ‘this.setState’ for local state, or dispatch an action to a reducer to manipulate the store.

Hopefully these basic rules offer some clarification on when to use the store and when to use state.

--

--