Sub topic 13
Tagged Templates in the Ecosystem: styled-components, lit, graphql-tag
Earlier chapters built small tags of your own: an HTML escaper, a SQL query builder, and a cache keyed on the strings array. Popular libraries use the same mechanics at scale. This chapter covers three of them, each of which interprets the strings and values differently, and closes with the gotchas that come from that.
The chapter assumes you already know:
- how a tag receives
stringsand...values - the
reduceinterleaving pattern - that the strings array is frozen and reused for each call site
- that tags can return non-string values
One Syntax, Three Interpretations
Every tagged template library makes the same split. The static parts are source text written in another language (CSS, HTML, or GraphQL). The values are holes in that text, and each library decides what goes in them.
| Library | Static parts are | Values are | Returns | Cache key |
|---|---|---|---|---|
| styled-components | CSS rules | Strings, or functions of props | A React component | Generated class name per style result |
| lit `html` | HTML markup | Data placed in text or attribute positions | A template result object | The strings array itself |
| graphql-tag `gql` | GraphQL source | Fragment documents or strings | A parsed AST (`DocumentNode`) | The normalized query text |
styled-components: Values as Functions of Props
In styled-components, styled.button is a member expression that evaluates to a tag function. A function placed in a ${} slot is not called when the template is evaluated. The library stores it and calls it with the component's props every time the component renders.
// Requires: npm install styled-components react
import styled from 'styled-components';
const Button = styled.button`
padding: 0.5em 1em;
color: ${(props) => (props.$primary ? 'white' : 'palevioletred')};
background: ${(props) => (props.$primary ? 'palevioletred' : 'white')};
`;
// <Button $primary>Save</Button>The tag returns a component, not a string. Below is a dependency-free sketch of the idea. It renders to an inline style attribute so the output is easy to see. The real library hashes the resolved CSS into a class name and injects a stylesheet into the page.
function styledTag(tagName) {
return (strings, ...interpolations) => (props) => {
const css = strings.reduce((out, str, i) => {
const v = interpolations[i - 1];
return out + (typeof v === 'function' ? v(props) : v) + str;
});
const style = css.trim().replace(/\s+/g, ' ');
return `<${tagName} style="${style}">${props.children}</${tagName}>`;
};
}
const styled = { button: styledTag('button') };
const Button = styled.button`
color: ${(p) => (p.primary ? 'white' : 'black')};
background: ${(p) => (p.primary ? 'navy' : 'white')};
`;
console.log(Button({ primary: true, children: 'Save' }));
// <button style="color: white; background: navy;">Save</button>
console.log(Button({ primary: false, children: 'Cancel' }));
// <button style="color: black; background: white;">Cancel</button>This is a tag that returns a function, which is the "tags can return anything" idea applied to a real problem. styled-components also uses chained tags. styled.button.attrs({ type: 'button' }) returns another tag, and so does styled(MyComponent). In every case, the thing just before the backtick is whatever that expression evaluates to.
lit: The Strings Array as a Template Identity
lit's html tag does not build a string at all. It returns a small object that holds the strings array and the values. When you render that object, lit checks whether it has seen this exact strings array before. Because the array is frozen and reused for each call site, an identity lookup is enough. On the first render lit parses the markup once into a <template> element and records where each hole sits. On later renders it only compares the new values with the old ones and updates the DOM nodes that changed.
// Requires: npm install lit (runs in a browser)
import { html, render } from 'lit';
const greet = (name) => html`<p>Hello, ${name}!</p>`;
render(greet('<b>Ada</b>'), document.body);
// The page shows the literal text <b>Ada</b>; no bold element is created.lit does not need an escapeHTML function like the one from the earlier chapter. It never concatenates values into markup. A value in a text position becomes the content of a text node, and a value in an attribute position is set as the attribute's value. The browser never parses either one as HTML.
Here is the caching mechanism in isolation:
const templateCache = new Map();
let prepareCount = 0;
function prepare(strings) {
prepareCount++;
return strings.join('<!--hole-->'); // stand-in for building a <template>
}
function html(strings, ...values) {
let template = templateCache.get(strings);
if (template === undefined) {
template = prepare(strings);
templateCache.set(strings, template);
}
return { template, values };
}
const greet = (name) => html`<p>Hello, ${name}!</p>`;
greet('Ada');
greet('Grace');
console.log(prepareCount); // 1: one call site, prepared once
console.log(greet('Linus').values); // [ 'Linus' ]
console.log(greet('Linus').template); // '<p>Hello, <!--hole-->!</p>'lit has a separate css tag for component styles, and it is stricter. It accepts only numbers and the results of other css calls. Any other value makes it throw an error that points you to unsafeCSS. Requiring an explicit opt-in for raw strings is a good design to copy in your own tags.
graphql-tag: Parsing at the Tag, Caching by Text
gql turns GraphQL source into an abstract syntax tree (AST), the DocumentNode that clients such as Apollo consume. It treats interpolated values specially. If a value is itself a parsed document, usually a fragment, gql inserts that document's source text. Any other value is pasted in as text. Then gql normalizes whitespace and looks up the result in a cache keyed by that string. Two different call sites that produce the same normalized text therefore get the same parsed object.
// Requires: npm install graphql graphql-tag
import gql from 'graphql-tag';
const USER_FIELDS = gql`
fragment UserFields on User { id name }
`;
const GET_USER = gql`
query GetUser($id: ID!) { user(id: $id) { ...UserFields } }
${USER_FIELDS}
`;A runnable sketch of the same idea, with parsing replaced by a placeholder object:
const docCache = new Map();
function gql(strings, ...values) {
const source = strings.reduce((out, str, i) => {
const v = values[i - 1];
return out + (v && v.kind === 'Document' ? v.source : String(v)) + str;
});
const key = source.replace(/\s+/g, ' ').trim();
if (!docCache.has(key)) {
docCache.set(key, { kind: 'Document', source: key }); // real code: parse(key)
}
return docCache.get(key);
}
const userFields = gql`fragment UserFields on User { id name }`;
const query = gql`
query GetUser { user(id: 1) { ...UserFields } }
${userFields}
`;
console.log(query.source);
// 'query GetUser { user(id: 1) { ...UserFields } } fragment UserFields on User { id name }'
console.log(gql`fragment UserFields on User { id name }` === userFields); // trueThis cache is keyed by text, not by the identity of the strings array. That choice suits gql because its output depends on the values as well as the static parts. lit can key on identity because it keeps the values apart and never combines them into the cached template.
Why Libraries Choose Tags
- The embedded language stays readable. Multiline CSS, HTML, or GraphQL sits in the file with no string concatenation or escaped quotes.
- Static parts can be trusted. The author wrote them in the source. Only the values come from outside, so the library can treat the two differently.
- The tag name tells tools what language is inside. Editor extensions highlight and lint the contents of
css,html, andgql, and Prettier formats several of these embedded languages. - Caching is cheap. Either the identity of the strings array (lit) or the joined text (graphql-tag) gives a ready-made cache key.
Gotchas When Moving Between Libraries
- The same syntax carries different safety guarantees. lit's
htmlis safe for text because of how it renders. A styled-components template is not escaped.gqlpastes plain string values into the query text. Find out what a specific tag does with values before you interpolate untrusted data. - Tooling depends on the tag's name. If you rename the import (
import { html as h } from 'lit') or wrap the tag in a helper, syntax highlighting and build-time compilation can stop working. - Functions mean different things. In styled-components, a function value is a prop callback. Other tags may convert a function to a string or reject it.
- Call-site caching assumes a literal. A lit template built dynamically gets no caching benefit, for example one built by calling
html(['<p>', '</p>'], x)with a fresh array each time. A template literal that you call many times inside a loop is still one call site.
Deciding Whether to Build Your Own Tag
Write a custom tag when all three of these are true:
- You are embedding another language.
- The static parts and the values need different treatment, such as escaping, binding, or parsing.
- A string-returning function would push callers to concatenate unsafe input.
If you only need formatting, an ordinary function call is clearer.
Exercise
A teammate writes const tpl = html(['<li>', '</li>'], item) inside a loop, calling lit's html as a normal function with a new array literal each iteration. Rendering still works, but performance drops. Why?
Show answer
lit caches prepared templates using the identity of the strings array. A real tagged template call site always passes the same frozen array, but a new array literal on each iteration is a different object every time. Each call misses the cache, so lit parses and prepares the template again. Using ` html<li>${item}</li> ` restores the single call site.
Exercise
Using the gql sketch from this chapter, what does gqlquery { a } === gqlquery { a }`` evaluate to, and would the same comparison be true under lit-style identity caching?
Show answer
It is true with the gql sketch. Both sources normalize to 'query { a }', so the second call returns the cached object. With identity caching the two call sites would have different strings arrays, so they would get two separate cache entries.
Exercise
Why does lit's css tag throw when you interpolate an ordinary string, while styled-components accepts one?
Show answer
lit's css tag treats a raw string value as potentially untrusted, so it requires an explicit opt-in through unsafeCSS. styled-components treats values as trusted CSS fragments and pastes them into the stylesheet as they are. The author is then responsible for validating any user-controlled value.