I am new to React and web development generally so please try to understand if the question seems dumb.
So, I am currently making a simple e-commerce app and I was thinking of using state management either using redux or react context.
However, I also thought if I have a database, why would I need global state management if I can retrieve the data or sessions I need from the database? For example, if need cart information for the currently logged-in user, I can retrieve it from the database, if I want information related to the order list, I can retrieve it from the database.
I know I am missing something because it doesn’t sound right to completely avoid using state management tools but at this point, I just don’t know when will I need such state management specifically in e-commerce.
Can you please tell me if there are situations where I would need to use state management?
In a nutshell, the client app states have little to do with the business data. Of course, some business data might be referred or held by the client’s state, but it’s contextual. Not mandatory.
When we refer to the client app state, we think about the last page visited, the last button clicked, pre-filled and unsubmitted forms, the number/badge of items in the cart, the number/badge of notifications in the built-in message inbox, etc. It’s somewhat a snapshot of the client at a given point in time.
For example, say the user was searching for products, filling the cart and, at some point, it goes afk; the token/session expires. When the user is back, the shop redirects to the login page. Allowing the user to continue with his/her activity/process from where it was haltered, will take you to “remember” a few things like: the last page, the last search, items in the cart, etc. By doing so, after the login, the app can fetch all this info and lead the user to the precise app state he/she was before going afk.
If you have multiple clients (web, mobile, tablet, smartwatch, etc.) and you want them to share the state, then the state can not be held by the client apps individually; it has to be sent to the server to allow other clients to synch and reproduce the same state. Whether the server persists this data in a database or in memory is an implementation detail.
Another use case is the offline mode. Say one of the clients goes offline due to connectivity issues. By managing the state on the client side, you allow the user to keep “buying” (filling the cart) until the connection is back or stable and the current state can be synced with other clients through the server.
Note that all of this is only relevant when the server (backend) is stateless or we want it to be so. No need to say that server and client states aren’t and don’t need to be the same. That’s another good reason for managing the client app state on the client side, to keep server-side complexity low.