Fix hydration error by this npm package

FAISAL HUSAINFAISAL HUSAIN
1 min read

If you have worked with or working with Next.js you have definitely came across this hydration error.

Fix Method ##1

Simple fix for this error is

 const [isMounted, setIsMounted] = useState(false);

  useEffect(() => {
    setIsMounted(true);
  }, []);

  if (!isMounted) {
    return null;
  }

just find the component which is causing hydration error and put this code in the beginning of the component error will be resolved.

Fix Method ##2

Second method is you can download a npm package which do the same this as told above but take out the pain of writing code again and again.

Link to package

Code how this package works

import useFixHydration from "fix-hydration"


const componentinwhichHydrationerroristhere = () => {

const hasMounted=useFixHydration()

if(!hasMounted){
 return null
}

return (
<div> After hydration is fixed <div/>
)

}

Below you can see I shifted my application code from method 1 to method 2

But you have to figure out which component is giving you hydration error and you can put this code in beginning.

If you want to read more about hydration error and how website like Airbnb also deal it with same way I taught you . You should read this article Perils of hydration

Code of the package

Thank you

0
Subscribe to my newsletter

Read articles from FAISAL HUSAIN directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

FAISAL HUSAIN
FAISAL HUSAIN

I am Full-stack developer from India. Welcome to my digital corner . I will post articles about things I learn on day to day basis