Hydration hooks
Write id and data-* hooks for client-side frameworks.
What is a hydration hook?
After a page is built on the server and reaches the browser, JavaScript sometimes wakes the HTML up and makes it interactive. That step is called hydration. The points JavaScript holds onto are hydration hooks: usually id and data-* attributes do the job.
For instance the server sends <div id="tabs">; JavaScript finds that id and wires tab behaviour. Likewise a <button data-target="#profile"> tells which panel it opens. These bridges let HTML come first and behaviour follow.
id and data-* together
In hydration hooks the two attributes do different jobs. An id picks a single point: it appears once on the page and JavaScript grabs it directly. A data-* carries a relation: which panel a button opens, which record a card represents.
Using both is common. For example <div id="profile-panel" data-role="panel"> carries both a unique point and a role. The rule to keep: an id appears once per page; never duplicate it. A data-* may sit on many elements with the same name.
Accessible hooks
Hooks serve accessibility too, not only JavaScript. An id underpins relations like <label for> and aria-labelledby. A <button aria-controls="profile-panel"> tells both the screen reader and JavaScript which panel it controls.
So a good hook serves more than one goal: it lets JavaScript find the point, explains the relation to the screen reader, and gives tests a stable anchor. HTML stays alive and accessible at once. Keep those three goals in mind when you write a hook.
Exercise Write a tabs skeleton
Write a tabs skeleton inside body: a <div id="tabs"> root holding a <button> with data-target="#panel-profile" and non-empty text, followed by a <section> with id="panel-profile". The section holds a non-empty <h2>. The button's aria-controls attribute also carries panel-profile.
Show example solution
<body>
<div id="tabs">
<button data-target="#panel-profile" aria-controls="panel-profile">Profile</button>
<section id="panel-profile">
<h2>Profile Details</h2>
</section>
</div>
</body>
Test yourself
-
Which one is a good hydration hook?
- A random class name
- A repeated piece of text
- A colour code
- A unique id on the page
Show answer
A unique id on the page — Correct. A unique id lets JavaScript find the exact point.
-
Complete the hook sentence
<p>JavaScript builds the bridge using the ____ that come from the server.</p>Show answer
<p>JavaScript builds the bridge using the id and data-* that come from the server.</p> -
Match each hook to its role
- id
- Picks a single point
- data-target
- Points to the target
- data-action
- Carries the task
- data-state
- Carries state info