notrab / react-use-cart

React hook library for managing cart state

Home Page:http://npm.im/react-use-cart

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

NextJS Hydration error

Soso966 opened this issue · comments

Hello,

When I use the cart library, I get a Hydration error:
next-dev.js:20 Warning: Expected server HTML to contain a matching in

.
Error: Hydration failed because the initial UI does not match what was rendered on the server.

image

I think I have fixed the error when Using useState and useEffect hooks in reactjs.

Hey @Soso966 there's another issue closed with some solutions to get around this with Next.js

#113

Happy to accept a PR if you have a solution that works for everyone.

Hey @Soso966 there's another issue closed with some solutions to get around this with Next.js

#113

Happy to accept a PR if you have a solution that works for everyone.

I am planning to create a hook called useCartItem and this will compose using useState and useEffect instead of implementing them on each page.

I managed to fix this issue by doing like the example below:

"use client";

import CartAdd from "./add-items"; // component
import CartContent from "./content"; // component
import { CartProvider } from "react-use-cart"; // lib
import { useEffect, useState } from 'react'; // lib

export default function CartPage() {
    const [isClient, setIsClient] = useState(false);

    useEffect(() => {
        // This will be executed only on the client side after the initial render
        setIsClient(true);
    }, []);

    // Render nothing on server-side
    if (!isClient) {
        return null;
    }

    return (
        <CartProvider>
            <CartContent />
            <CartAdd />
        </CartProvider>
    );

}