Next.js Discord

Discord Forum

useState outside of function causes page to refresh

Answered
Lithuanian Hound posted this in #help-forum
Open in Discord
Lithuanian HoundOP
Hello.
I'm using latest nextjs in an app directory.

I have function with a combobox, but whenever I set the open/setOpen useState outside of the function the whole page refreshes (it seems like, the loading is triggered).
This doesn't happen when the useState is inside the function. I can't elevate the state because of this.
Answered by Clown
You can try passing the value down too through parameter
View full answer

7 Replies

Lithuanian HoundOP
When useState is inside the function:
https://i.imgur.com/ta33jb2.gif
When useState is outside the function:
https://i.imgur.com/SVQYsSW.gif
Hooks arent supposed to be outside the component(in this case the function)
You need to use hooks inside the functional component
Lithuanian HoundOP
Should I use context then to retrieve the value to apply filter?
You can try passing the value down too through parameter
Answer
Otherwise you can use context