Have you received the following error while using local storage in Next.js?
ReferenceError: localStorage is not defined
Enter full...
For further actions, you may consider blocking this person and/or reporting abuse
from next js 13 you must use
on top of the file
and it will work without any error and it's more cleaner solution
It will have an error in development mode since the component would still run on the server
does 'use client' works with nextjs pages? I'm a bit confused
Yes, it works on the new routes folder. Where all the components are server components by default. You need to specify
use client
To make it as a client side component
sorry I mean pages router not nextjs pages, is it an app router thing only?
This must be a joke.
How bad the framework needs to be if you can't use localstorage in 1 line of code.
How good framework needs to be if you can use local storage with a server side rendering.
I think conceptually its important to understand that you need to save the form data to local storage when the form field data changes during a client event (like submitting the form or making changes to form fields). With pure react you were able to update local storage using useEffect when the form object changes but this wont work in NextJS because the form object will clear (and hence nullify form fields in local storage) on initial component load before hydrating the client.
Takeaway approach (which is provided in this article): One useEffect to retrieve the local storage value if local storage is populated, and only write to local storage during a client event.
really helpful post!
Thanks for this. working code.
how to use Middle ware localstorage ?
Thank you for the useful hook, it works perfectly!
custom hook method is not working🥲
source code: github.com/collegewap/next-local-s...
Demo: next-local-storage.vercel.app/
Hope it helps