Reputation: 3836
In a react js project there are multiple ways to store data .
1 . Using redux state management with redux persist to store data forever in the browser .
2 . Using web browser's Local storage by using setter and getters .
3 . Using web Cookies .
I was wondering whats the difference between all these ways on storing data and When to use what for storing data ?
Upvotes: 1
Views: 1250
Reputation: 751
There're some rather inaccurate statements in your question. Re:1 - redux doesn't persist data forever in browser. This is actually what localStorage, cookies and local DB does.
But with that correction in mind, it's a good question.
redux state is the most "reactive" one. It's aim is to let components within your app to have access to the "single source of truth". It stores data directly in JS, in memory. It can be quickly accessed and updated by your components, without any medium (like local storage), that's why it's handy for it's purposes.
local storage indeed is capable in storing data in your browser forever. However, reading from it and writing to it takes extra time and burden in order to keep data sync, because you can't interact with it synchronously, it's not the best choice for using as primary data source for your component. But it's good to hydrating some data on app inits (for example, you can store the JWT token there, and then hydrate it into the redux store in app load - it's a common pattern)
Cookies is not a good place to store the info in broad sense. It's rather a placeholder for storing some session-specific identifiers for communicating them to your backend. Check out this one for more info: https://medium.com/datadriveninvestor/cookies-vs-local-storage-2f3732c7d977#:~:text=Differences%20between%20cookies%20and%20localStorage&text=Cookies%20are%20mainly%20for%20reading,you%20more%20to%20work%20with.
Upvotes: 2