skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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 in projectNamesrcappsomepagepage.js :

    import SomeComponent from "../comp/SomeComponent"
    
    const page = () => {
        return (
            <div>
                <h1>A Page </h1>
                <SomeComponent />
    
                <p>Rest of the page is server-side rendered !</p>
                <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Reiciendis totam vero, laudantium nihil quae, distinctio officia quaerat neque maxime voluptatem ipsam. Quia unde quo deleniti.</p>
            </div>
        )
    }
    
    export default page
    

    SomeComponent.js is a component in (components folder) projectNamesrcappcompSomeComponent.js :

    'use client'
    import React, { useEffect, useMemo, useState } from 'react'
    
    const SomeComponent = () => {
    
        const [Counter, SetCounter] = useState(0)
    
        const Double = useMemo(() => Counter * Counter, [Counter])
        // RETURNS DOUBLE OF COUNTER
    
        useEffect(() => {
            console.log("Page Rendered !!");
        }, [])
        // RUNS ONE TIME
    
        return (
            <div>
                Counter : {Counter}
                <div>
                    Double : {Double}
                </div>
                <div>
                    <button onClick={() => SetCounter(Counter + 1)}>+</button>
                    <button onClick={() => SetCounter(Counter - 1)}>-</button>
                </div>
            </div>
        )
    }
    
    export default SomeComponent
    

    Please Read :

    If you still have any doubts, leave a comment.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search