What is the proper way to implement the "useEffect" front-end functionality in Next.JS server components?
Tried to use useEffect in the server side but it does not work. Do the usage of any other hooks work in the server side? If not, how can I implement a function that watches for changes on a variable, and performs an action when this change happened?
2
Answers
UseEffect is actually a client side hook you cannot use it on the server you have to make that component a client component to use hooks like useEffect, useState, any click events, any form events etc.
You can make a component client by writing
"use client"
on top of your code ie, first line.Be aware using a use client directive will make all child components client components and will be rendered on user side affecting some performance so it is advised to keep your client components at the leaves of your tree.
Here is a small code I made :
I’m using App Router, there are 2 types of routers & folder structure & file conventions are different for both.
page.js
inprojectNamesrcappsomepagepage.js
:SomeComponent.js
is a component in (components folder)projectNamesrcappcompSomeComponent.js
:Please Read :
'use client'
: https://react.dev/reference/react/use-client