Skip to content

Commit 92e50a7

Browse files
committed
Start dsfr client side in useEffect in Next.js for avoiding hydratation errors
1 parent 788911d commit 92e50a7

File tree

2 files changed

+26
-9
lines changed

2 files changed

+26
-9
lines changed

src/lib/start.ts

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,10 @@ export async function startDsfrReact(params: Params) {
3636
setLangToUseIfProviderNotUsed(langIfNoProvider);
3737
}
3838

39-
const isNextJsDevEnvironnement = (window as any).__NEXT_DATA__?.buildId === "development";
39+
const isNextJs = (window as any).__NEXT_DATA__ !== undefined;
40+
41+
const isNextJsDevEnvironnement =
42+
isNextJs && (window as any).__NEXT_DATA__.buildId === "development";
4043

4144
set_html_color_scheme_attributes: {
4245
if (document.documentElement.getAttribute(data_fr_theme) !== null) {
@@ -82,12 +85,9 @@ export async function startDsfrReact(params: Params) {
8285

8386
await import("../dsfr/dsfr.module" as any);
8487

85-
if (isNextJsDevEnvironnement) {
86-
// NOTE: @gouvfr/dsfr/dist/dsfr.module.js is not isomorphic, it can't run on the Server.",
87-
// We set an artificial delay before starting the module otherwise to avoid getting",
88-
// Hydration error from Next.js
89-
await new Promise(resolve => setTimeout(resolve, 400));
90-
}
88+
console.log("disabled");
9189

92-
(window as any).dsfr.start();
90+
if (!isNextJs) {
91+
(window as any).dsfr.start();
92+
}
9393
}

src/next.tsx

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React from "react";
1+
import React, { useEffect } from "react";
22
import Head from "next/head";
33
import type { NextComponentType } from "next";
44
import DefaultApp from "next/app";
@@ -150,6 +150,23 @@ export function createNextDsfrIntegrationApi(params: Params): NextDsfrIntegratio
150150
colorScheme = "light";
151151
}
152152

153+
useEffect(() => {
154+
if (!isBrowser) {
155+
return;
156+
}
157+
const { dsfr } = window as any;
158+
159+
const isStarted = "isStarted";
160+
161+
if (dsfr[isStarted] === true) {
162+
return;
163+
}
164+
165+
dsfr.start();
166+
167+
dsfr[isStarted] = true;
168+
}, []);
169+
153170
return (
154171
<>
155172
<Head>

0 commit comments

Comments
 (0)