Skip to content

Commit

Permalink
fix(react): update useId to match id on server and client (#6369)
Browse files Browse the repository at this point in the history
Co-authored-by: Andrea N. Cardona <andreancardona@gmail.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
  • Loading branch information
3 people authored Jul 9, 2020
1 parent 555038d commit 6d3e3dc
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 3 deletions.
23 changes: 23 additions & 0 deletions packages/react/src/internal/__tests__/useId.server-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/**
* Copyright IBM Corp. 2016, 2020
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*
* @jest-environment node
*/

import React from 'react';
import { renderToString } from 'react-dom/server';
import { useId } from '../useId';

describe('useId SSR', () => {
it('should not generate an id on the server', () => {
function Test() {
const id = useId('test');
return <span id={id}>test</span>;
}
const markup = renderToString(<Test />);
expect(markup.indexOf('id="')).toBe(-1);
});
});
53 changes: 50 additions & 3 deletions packages/react/src/internal/useId.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,64 @@
* LICENSE file in the root directory of this source tree.
*/

import { useRef } from 'react';
// This file was heavily inspired by Reach UI and their work on their auto-id
// package
// https://github.com/reach/reach-ui/blob/86a046f54d53b6420e392b3fa56dd991d9d4e458/packages/auto-id/src/index.ts
//
// The problem that this solves is an id mismatch when auto-generating
// ids on both the server and the client. When using server-side rendering,
// there can be the chance of a mismatch between what the server renders and
// what the client renders when the id value is auto-generated.
//
// To get around this, we set the initial value of the `id` to `null` and then
// conditionally use `useLayoutEffect` on the client and `useEffect` on the
// server. On the client, `useLayoutEffect` will patch up the id to the correct
// value. On the server, `useEffect` will not run.
//
// This ensures that we won't encounter a mismatch in ids between server and
// client, at the cost of runtime patching of the id value in
// `useLayoutEffect`

import { useEffect, useLayoutEffect, useState } from 'react';
import setupGetInstanceId from '../tools/setupGetInstanceId';

const getId = setupGetInstanceId();
const useIsomorphicLayoutEffect = canUseDOM() ? useLayoutEffect : useEffect;

function canUseDOM() {
return !!(
typeof window !== 'undefined' &&
window.document &&
window.document.createElement
);
}

let serverHandoffCompleted = false;

/**
* Generate a unique ID with an optional prefix prepended to it
* @param {string} [prefix]
* @returns {string}
*/
export function useId(prefix = 'id') {
const ref = useRef(`${prefix}-${getId()}`);
return ref.current;
const [id, setId] = useState(() => {
if (serverHandoffCompleted) {
return `${prefix}-${getId()}`;
}
return null;
});

useIsomorphicLayoutEffect(() => {
if (id === null) {
setId(`${prefix}-${getId()}`);
}
}, [getId]);

useEffect(() => {
if (serverHandoffCompleted === false) {
serverHandoffCompleted = true;
}
}, []);

return id;
}

0 comments on commit 6d3e3dc

Please sign in to comment.