Next.js Discord

Discord Forum

Hydration error: What did I do wrong

Answered
Anay-208 posted this in #help-forum
Open in Discord
I'm getting hydration error. Here is my code snippet:
Answered by ᴉuɐpɹɐɐ
const [mounted, setMounted] = useState(false)
useEffect(()=>{setMounted(true)},[])
return mounted ? <content> : null
View full answer

9 Replies

    return (
        <main className="min-h-screen main-nav">
            <h1 className="heading">Cart</h1>
            {cartItems?.length <= 0 ? 
            <p className="subheading">Your Cart Is Currently Empty.</p> : 
            cart.length > 0 ? cart.map(item => (
                <div>
                    {JSON.stringify(item)}
                </div>
            )) : <Loading className={"mt-4"} />  }
        </main>
    )
In the above code if I remove this
- cartItems?.length <= 0 ? 
- <p className="subheading">Your Cart Is Currently Empty.</p> 
- : cart.length > 0 ?
The hydration error is gone
    const [cartItems, setCartItems] = useLocalStorage<CartItem[]>("cart", []); // imported from usehooks-ts
    const [cart, setCart] = useState<CartItemLite[]>([]);
@Anay-208 tsx return ( <main className="min-h-screen main-nav"> <h1 className="heading">Cart</h1> {cartItems?.length <= 0 ? <p className="subheading">Your Cart Is Currently Empty.</p> : cart.length > 0 ? cart.map(item => ( <div> {JSON.stringify(item)} </div> )) : <Loading className={"mt-4"} /> } </main> )
because when the page rendering on server, it rendered Your Cart Is Currently Empty.
then the server send the data to client and when it hydrate on client, it load the cartItem from localstorage and rendering the item with different result
@Anay-208 What can I do then?
make sure that part is only rendered in the client, or make sure server data mathces.
@ᴉuɐpɹɐɐ make sure that part is only rendered in the client, or make sure server data mathces.
How can I make sure that part only renders in the client
const [mounted, setMounted] = useState(false)
useEffect(()=>{setMounted(true)},[])
return mounted ? <content> : null
Answer