import { createContext, useEffect, useState } from 'react';
export const CartContext = createContext({});
export function CardContextProvider({ children }) {
const [cartProducts, setCartProducts] = useState([]);
useEffect(() => {
if (typeof window !== "undefined") {
const localStorageData = window.localStorage.getItem('cartProducts');
if (localStorageData) {
setCartProducts(JSON.parse(localStorageData));
}
}
}, []);
useEffect(() => {
if (typeof window !== "undefined") {
window.localStorage.setItem('cartProducts', JSON.stringify(cartProducts));
}
}, [cartProducts]);
function addProduct(productId) {
setCartProducts([...cartProducts, productId]);
}
function removeProduct(productId) {
const index = cartProducts.findIndex((id) => id === productId);
if (index !== -1) {
const newCartProducts = [...cartProducts];
newCartProducts.splice(index, 1);
setCartProducts(newCartProducts);
}
}
return (
<CartContext.Provider value={{ cartProducts, setCartProducts, addProduct, removeProduct }}>
{children}
</CartContext.Provider>
);
}
What can cause this warning? I tried to avoid all things presented here and I am still encountering this error. I am using next.js, tailwind and styled components.
Problem :
Nextjs hydration : cannot write a title without error
Possible Cause :
next.config.js
Possible Solution :
Add 'use client' directive at top of file in CardContextProvider
Disable all browser extensions,
Add styledComponents: true,
in next.config.js
:
/** @type {import('next').NextConfig} */
const nextConfig = {
...
compiler: {
styledComponents: true,
},
};
module.exports = nextConfig;
Please Read :
'use client' : https://react.dev/reference/react/use-client
Example app with styled-components : https://github.com/vercel/next.js/tree/canary/examples/with-styled-components
With SWC: https://styled-components.com/docs/advanced#next.js
If using App router in NextJS : https://styled-components.com/docs/advanced#app-directory
If you have any doubts, then please leave a comment (I will update answer if necessary)