State Management in Next.js without the use of RTK or any other state Management library if possible
Answered
Chinese Alligator posted this in #help-forum
Chinese AlligatorOP
hey, i have large scale app the same i talked about before, and just like you said i'm gonna avoid use of RTK. So how do i achieve cross component data sharing, like we use to do in RTK, e.g. dispatch a add to cart from a component and reflecting it on the cart icon on completely different part of the Tree. How should i go about it next.js App router without use of RTK or any state management library for that. Or the use of such library is essential in such scenario. Any suggestion is appreciated
Answered by Clown
OR you can store the cart inside your db, cache its result and revalidate on change.
These are all the ways you can go about it
These are all the ways you can go about it
7 Replies
Sun bear
You could do it with useContext.
so that you can access it like this
cart could contain all items so that you can access it everywhere. In this case you should store the cart in cookie or database to make sure that the cart is not empty on refresh
so that you can access it like this
const {cart, addToCart} = useCart();cart could contain all items so that you can access it everywhere. In this case you should store the cart in cookie or database to make sure that the cart is not empty on refresh
Chinese AlligatorOP
so there is not any way that i could by pass current state management soln like redux and context?
If the state was simple i would have told you to just use search params but for more complex state like this you can either use State Management solutions like redux/zustand/react context or use things like cookies if you want to go full SSR.
Technically you can also go the localStorage way which would require some Client Side Rendering instead but is less tedious to use without the blaring disadvantage that cookies have(size limit).
OR you can store the cart inside your db, cache its result and revalidate on change.
These are all the ways you can go about it
These are all the ways you can go about it
Answer
@Clown OR you can store the cart inside your db, cache its result and revalidate on change.
These are all the ways you can go about it
Chinese AlligatorOP
so lets say i make changes in db and revalidate('/') will it re-render all the app?
Plott Hound
if you set the initial state as the fetched data you are passing to the component then it should rerender accordingly, if not you can use a useEffect to listen to changes on the data and update the state accordingly