Skip to content

Hydration Failure with useId() and AG Grid Enterprise

Core Problem

When using the useId() hook in a Next.js application that imports AG Grid Enterprise, hydration fails due to inconsistent _id values returned on the server versus the client.

Solution & Analysis

Reproducing the Issue

To reproduce this issue, follow these steps:

  1. Clone the provided GitHub repository: https://github.com/rwalisa/nextjs-useid-hydration-bug-demo/
  2. Start the application in development mode using npm run dev or build and run the server using npm run start
  3. Open the index page in your preferred web browser
  4. If the error doesn't appear, refresh the page
  5. Remove line 7 in Component.jsx to isolate the issue
  6. Refresh the page again to see that the error is gone

Code Insights

// Component.jsx
import { useId } from 'react';
import { agGridEnterprise } from '@ag-grid-enterprise/core';

const Component = () => {
  const _id = useId('my-id');
  // ...
};

In this example, useId() is used to generate a unique _id for the component. However, when AG Grid Enterprise is imported and referenced in the code, hydration fails due to inconsistent _id values.

Solution

To resolve this issue, you can use the useMemo hook to memoize the _id value generated by useId() on the client-side:

import { useMemo } from 'react';
import { agGridEnterprise } from '@ag-grid-enterprise/core';

const Component = () => {
  const _id = useMemo(() => useId('my-id'), []);
  // ...
};

By memoizing the _id value, we ensure that it is only generated once on the client-side and is not affected by the hydration process.

Conclusion

In conclusion, when using useId() in a Next.js application that imports AG Grid Enterprise, hydration fails due to inconsistent _id values. By isolating the issue with the provided GitHub repository and using the useMemo hook to memoize the _id value, we can resolve this issue and ensure stable hydration.

Reference