Skip to content

SSR-safe ID generation #7517

@illright

Description

@illright

Describe the problem

There are many cases where an application needs to connect DOM nodes with IDs:

  • form fields and labels (for)
  • accessible names (aria-labelledby)
  • more presented here

Given that these IDs do not need any semantic meaning, and given that humans are pretty terrible at coming up with app-level unique IDs, this is a job wonderfully suited for a framework. Taking SSR into consideration, we cannot simply use counter-based solutions or randomly generated IDs.

Describe the proposed solution

React 18 shipped its new useId() hook which allows utilizing all the component tree knowledge of the framework and using that to generate IDs that are stable across SSR and unique across component instances.

I would like to see a similar thing in Svelte. It could look like this (createInstanceId):

<!-- sign-in-form.svelte -->
<script lang="ts">
  import { createInstanceId } from 'svelte';
  
  const id = createInstanceId();
  const usernameID = `${id}-username`;
  const passwordID = `${id}-password`;
</script>

<label for={usernameID}>Username</label>
<input id={usernameID} />

<label for={passwordID}>Password</label>
<input id={passwordID} type="password" />

Alternatives considered

Variable

The ID could come from a compiler-populated instance-specific variable:

<label for={$$id}>Username</label>
<input id={$$id} />

Another name could be $$instanceId, to reflect its instance-dependency. This isn't perfect though, as it still doesn't communicate clearly enough that this isn't a component-specific variable, but rather an instance-specific one. A function call communicates that much better, similarly to createEventDispatcher()

Userland solution

I have used naive ID-generation solutions in the past (namely, lukeed/uid) and they didn't seem to cause any visible issues, but it's very likely that I simply haven't run into a use-case where a mismatch between the client and the server would be a problem.

Other userland solutions involve contexts, which is not great for developer experience, and might be problematic for asynchronous rendering (see reactwg/react-18#111 (reply in thread))

Importance

would make my life easier

Relevant mentions

#6932

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy