I have been learning React recently, I tried to build a small web-app for learning React. I have doubt regarding the state management.
I am not using anying library for state management now and also I am not using any DB. I want to understand which is best way to maintain state.
// index.js
...
<Routes>
<Route exact path="/" element={<App/>}></Route>
<Route exact path="/cart" element={<Cart/>}></Route>
</Routes>
...
// App.js
function App() {
...
// fetch Product data -> productData
// update Cart data -> cartData
<Product data={productData} {updateCart} />
...
}
// Cart.js
function Cart() {
...
<Cart data={cartData} />
...
}
Consider on the above snippet.
I have two page
Product page
Cart Page
I am fetching the data in Product page and when the product is added to the cart then I will update ‘cardData’. Now I want to use the ‘cartData’ in the Cart page.
What is the best way to achieve it ? I thought about storing it in cache. If there is DB we can store it.
2
Answers
In this scenario the best way to store your data would be the
localStorage
. There you should define a key for the cart, and your value would be an array with the products in your cart.In ReactJS this is how you can access the
localStorage
:As you said, if you have DB, you should store your this data in DB.
Typically you’d use a wrapper to manage state and API calls. But if you have multiple pages that need access to the same state then look into react useContext which is essentially a way of creating a global state.