ref vs useState
I'm a bit confused on the useState function, when do it use it and does it completely replace ref?
5 Replies
You would use
useState
when you need to share state between the server and client. Ref is safe to use on the client-side, but on the server it could lead to data leaking between requests.
I'd say in most cases you'd probably want to use useState
?Ok so if the server makes changes to it you would want to use
useState
and let's say you want to keep track of a user selected item ref is fineA good example is using a random value, say a generated uuid.
If you use a ref and both the server and client would use
const foo = ref(uuid())
then there would be a hydration missmatch, as both the client and server generate their own uuid.
However with const foo = useState('randomId', () => uuid())
Nuxt3 makes sure those values are synced between server and client
Correct, it's mostly useful for more "global" types of state that might be shared between pages/components and requestsOk great this clears it up
👍
(not 100% sure about the request part btw)
I think it's still unqiue per request, but is more a way to make sure server and client are in sync