A performant client-side syntax highlighting component and hook for React, built with Shiki.
- 🎨 react-shiki
- 🖼️ Provides both a
ShikiHighlightercomponent and auseShikiHighlighterhook for more flexibility - 🔐 Flexible output: Choose between React elements (no
dangerouslySetInnerHTML) or HTML strings - 📦 Multiple bundle options: Full bundle (~1.2MB gz), web bundle (~707KB gz), or minimal core bundle for fine-grained bundle control
- 🖌️ Full support for custom TextMate themes and languages, passed as objects or dynamic imports
- 🧬 Automatic highlighting of embedded languages (e.g. TypeScript fenced inside Markdown) via Shiki's
guessEmbeddedLanguages - 🔧 Supports passing custom Shiki transformers to the highlighter, in addition to all other options supported by
codeToHast - 🚰 Performant highlighting of streamed code, with optional throttling
- 📚 Includes minimal default styles for code blocks
- 🚀 Shiki dynamically imports only the languages and themes used on a page for optimal performance
- 🖥️
ShikiHighlightercomponent displays a language label for each code block whenshowLanguageis set totrue(default) - 🎨 Customizable styling of generated code blocks and language labels
- 📏 Optional line numbers with customizable starting number and styling
npm i react-shikiYou can use either the ShikiHighlighter component or the useShikiHighlighter hook to highlight code.
Using the Component:
import ShikiHighlighter from "react-shiki";
function CodeBlock() {
return (
<ShikiHighlighter language="jsx" theme="ayu-dark">
{code.trim()}
</ShikiHighlighter>
);
}Using the Hook:
import { useShikiHighlighter } from "react-shiki";
function CodeBlock({ code, language }) {
const highlightedCode = useShikiHighlighter(code, language, "github-dark");
return <div className="code-block">{highlightedCode}</div>;
}react-shiki, like shiki, offers three entry points to balance convenience and bundle optimization:
import ShikiHighlighter from 'react-shiki';- Size: ~6.4MB minified, ~1.2MB gzipped (react-shiki itself: ~9KB minified, ~4KB gzipped)
- Languages: All Shiki languages and themes
- Exported engines:
createJavaScriptRegexEngine,createJavaScriptRawEngine - Use case: Unknown language requirements, maximum language support
- Setup: Zero configuration required
import ShikiHighlighter from 'react-shiki/web';- Size: ~3.8MB minified, ~707KB gzipped (react-shiki itself: ~9KB minified, ~4KB gzipped)
- Languages: Web-focused languages (HTML, CSS, JS, TS, JSON, Markdown, Vue, JSX, Svelte)
- Exported engines:
createJavaScriptRegexEngine,createJavaScriptRawEngine - Use case: Web applications with balanced size/functionality
- Setup: Drop-in replacement for main entry point
import ShikiHighlighter, {
createHighlighterCore, // re-exported from shiki/core
createOnigurumaEngine, // re-exported from shiki/engine/oniguruma
createJavaScriptRegexEngine, // re-exported from shiki/engine/javascript
} from 'react-shiki/core';
// Create custom highlighter with dynamic imports to optimize client-side bundle size
const highlighter = await createHighlighterCore({
themes: [import('@shikijs/themes/nord')],
langs: [import('@shikijs/langs/typescript')],
engine: createOnigurumaEngine(import('shiki/wasm'))
// or createJavaScriptRegexEngine()
});
<ShikiHighlighter highlighter={highlighter} language="typescript" theme="nord">
{code}
</ShikiHighlighter>- Size: ~9KB minified (~4KB gzipped) + your imported themes/languages
- Languages: User-defined via custom highlighter
- Use case: Production apps requiring maximum bundle control
- Setup: Requires custom highlighter configuration
- Engine options: Choose JavaScript engine (smaller bundle, faster startup) or Oniguruma (WASM, maximum language support)
Shiki offers three built-in engines for syntax highlighting:
| Engine | Payload (gzip) | Startup | Grammar support |
|---|---|---|---|
| Oniguruma (default) | ~150 KB (466 KB WASM) | fetch + compile WASM | Reference engine, all grammars |
| JavaScript RegExp | ~20 KB | none, plain JS | All built-in languages (compatibility table); strict by default |
| JavaScript Raw | ~1 KB | none | Pre-compiled grammars only, has a known bug |
Payload sizes measured against shiki 4.3.0: onig.wasm is 466 KB (149 KB gzipped), the JavaScript engine's pattern transpiler (oniguruma-to-es) is 57 KB (20 KB gzipped), and the raw engine skips the transpiler entirely. Beyond the smaller download, the JavaScript engine also starts instantly (no WASM fetch and compile) and runs patterns as native JavaScript RegExp, which is faster for some languages.
The full and web bundles use Oniguruma by default. You can swap to the JavaScript engine by passing 'javascript' to engine. react-shiki creates and caches the engine internally, no need to import it, no WASM fetch with 'javascript', and it's safe to pass inline:
// Hook
const highlightedCode = useShikiHighlighter(code, 'typescript', 'github-dark', {
engine: 'javascript'
});
// Component
<ShikiHighlighter language="typescript" theme="github-dark" engine="javascript">
{code}
</ShikiHighlighter>Note
The underlying highlighter is a singleton created on the first highlight, so pass the same engine at every call site; mixed engines resolve to whichever highlighted first.
To customize engine configuration beyond the named defaults, pass an engine instance. Create it once at module scope; this avoids recreating new instances on every render, which would defeat memoization:
import { useShikiHighlighter, createJavaScriptRegexEngine } from 'react-shiki';
// Ensure this is at the module scope: created once, stable across renders
const engine = createJavaScriptRegexEngine({ forgiving: true });
const highlightedCode = useShikiHighlighter(code, 'typescript', 'github-dark', {
engine
});The JavaScript engine is strict by default: it throws when a grammar uses patterns it can't convert. forgiving: true skips those patterns for best-effort output. It also accepts target and regexConstructor, see Shiki - RegExp Engines for details.
The JavaScript Raw engine works the same way, but only with pre-compiled languages (@shikijs/langs-precompiled). The full and web bundles don't support the raw engine because they bundle standard grammars, you need a custom highlighter.
Important
Heads up: in a future release, react-shiki's default engine will be swapped from Oniguruma WASM to the JavaScript engine (with forgiving enabled by default).
Named engines ('javascript', 'oniguruma') don't apply to the core bundle since you create the highlighter with createHighlighterCore; instead, use createJavaScriptRegexEngine or createOnigurumaEngine to create a custom engine instance:
import {
createHighlighterCore,
createOnigurumaEngine,
createJavaScriptRegexEngine
} from 'react-shiki/core';
const highlighter = await createHighlighterCore({
themes: [import('@shikijs/themes/nord')],
langs: [import('@shikijs/langs/typescript')],
engine: createJavaScriptRegexEngine() // or createOnigurumaEngine(import('shiki/wasm'))
});The JavaScript Raw engine is the smallest option at only ~1 KB, but requires pre-compiled languages, and faces a known upstream bug -- shikijs/shiki:issue#918 -- causing some languages (Python, HTML, Perl, and YAML among those reported) to highlight incorrectly.
import {
useShikiHighlighter,
createHighlighterCore,
createJavaScriptRawEngine,
} from 'react-shiki/core';
// Module scope: raw engine + pre-compiled grammars, smallest and fastest
const highlighter = await createHighlighterCore({
themes: [import('@shikijs/themes/github-dark')],
langs: [import('@shikijs/langs-precompiled/typescript')],
engine: createJavaScriptRawEngine()
});
const highlightedCode = useShikiHighlighter(code, 'typescript', 'github-dark', {
highlighter
});Be sure to verify your language highlights correctly if you choose to use the raw engine (shikijs/shiki:issue#918).
react-shiki can return highlighted code in three formats:
React Nodes (Default) - Rendered as React elements, no dangerouslySetInnerHTML required
// Hook
const highlightedCode = useShikiHighlighter(code, "tsx", "github-dark");
// Component
<ShikiHighlighter language="tsx" theme="github-dark">
{code}
</ShikiHighlighter>HTML String - Rendered via dangerouslySetInnerHTML
// Hook (returns HTML string, use dangerouslySetInnerHTML to render)
const highlightedCode = useShikiHighlighter(code, "tsx", "github-dark", {
outputFormat: 'html'
});
// Component (automatically uses dangerouslySetInnerHTML when outputFormat is 'html')
<ShikiHighlighter language="tsx" theme="github-dark" outputFormat="html">
{code}
</ShikiHighlighter>Shiki Tokens (Experimental) - Hook-only output (bring your own renderer, react-shiki does not provide one)
const highlighted = useShikiHighlighter(code, "tsx", "github-dark", {
outputFormat: "tokens",
});
// Sample only, not a production renderer: you own rendering, memoization,
// and commit management (critical for streaming highlighting)
const rendered = highlighted?.tokens.map((line, i) => (
<div key={i}>
{line.map((token, j) => (
<span key={j} style={{ color: token.color }}>
{token.content}
</span>
))}
</div>
));The React and HTML formats spend their rendering work in different phases. HTML output skips per-token React element creation and reconciliation, reducing render-phase overhead for large, one-shot highlights, but each update replaces the code block's entire DOM subtree via innerHTML. React output pays for element creation and diffing on every update, but commits only incremental DOM mutations, minimizing DOM churn for frequently re-highlighted code such as streaming LLM output.
HTML output hands the highlighted markup to the DOM via dangerouslySetInnerHTML, so only use it with trusted code sources. The default React output is the safe choice for untrusted content.
Token output is for when you need to own rendering yourself; it is intentionally available on the hook, not the ShikiHighlighter component, since react-shiki's markup-based features no longer apply once you control the markup. Note that Shiki's codeToTokens does not run transformers or decorations, so markup-producing options, including transformers, decorations, line numbers, and structure, have no effect on token output.
The core inputs, positional arguments on the hook, props/children on the component:
| Input | Type | Default | Description |
|---|---|---|---|
code |
string |
- | Code to highlight |
language |
string | object |
- | Language to highlight, built-in or custom TextMate grammar object |
theme |
string | object |
'github-dark' |
Single or multi-theme configuration, built-in or custom TextMate theme object |
| Option | Type | Default | Description |
|---|---|---|---|
delay |
number |
- | Minimum time between highlights (in milliseconds), no throttling by default |
engine |
'javascript' | 'oniguruma' | RegexEngine |
'oniguruma' |
RegExp engine for syntax highlighting; named engines are created and cached internally |
highlighter |
Highlighter | HighlighterCore |
- | Custom highlighter instance, required for the core bundle |
outputFormat |
string |
'react' |
Output format: 'react' for React nodes, 'html' for HTML string, or 'tokens' for Shiki tokens (hook only, experimental) |
preloadLanguages |
array |
[] |
Preload bundled language IDs, custom grammar objects, or dynamic grammar imports |
customLanguages |
array |
[] |
Deprecated: use preloadLanguages instead. |
showLineNumbers |
boolean |
false |
Display line numbers alongside code |
startingLineNumber |
number |
1 |
Starting line number when line numbers are enabled |
highlightLineNumbers |
number[] |
- | Displayed line numbers to highlight |
All of Shiki's options pass-through and are accessible in react-shiki.
Based on outputFormat:
'tokens': All options supported by Shiki'scodeToTokens'html': All options supported by Shiki'scodeToHtml'react': All options supported by Shiki'scodeToHast
Commonly used:
transformers: modify the highlighting output with Shiki transformers (default:[])decorations: wrap ranges of highlighted tokens (default:[])defaultColor: default theme mode with multi-theme,falseto disable (default:'light')cssVariablePrefix: prefix for theme color CSS variables (default:'--shiki-')langAlias: map custom language names to bundled ones (default:{})structure:'classic'or'inline'HAST/HTML shape (default:'classic')tabindex: tab index of the code block (default:0)meta: arbitrary metadata passed to transformers (default:{})
The ShikiHighlighter component offers minimal built-in styling and customization options out-of-the-box:
| Prop | Type | Default | Description |
|---|---|---|---|
showLanguage |
boolean |
true |
Displays language label in top-right corner |
addDefaultStyles |
boolean |
true |
Adds minimal default styling to the highlighted code block |
as |
string |
'div' |
Component's Root HTML element |
className |
string |
- | Custom class name for the code block |
langClassName |
string |
- | Class name for styling the language label |
style |
object |
- | Inline style object for the code block |
langStyle |
object |
- | Inline style object for the language label |
react-shiki uses Shiki's guessEmbeddedLanguages to automatically detect, load, and highlight languages nested inside other languages. For example, a TypeScript fenced code block inside a Markdown document will be highlighted as TypeScript without any extra configuration. Embedded languages are dynamically loaded on demand, as long as they exist in your bundle.
To use multiple theme modes, pass an object with your multi-theme configuration to the theme prop in the ShikiHighlighter component:
<ShikiHighlighter
language="tsx"
theme={{
light: "github-light",
dark: "github-dark",
dim: "github-dark-dimmed",
}}
defaultColor="dark"
>
{code.trim()}
</ShikiHighlighter>Or, when using the hook, pass it to the theme parameter:
const highlightedCode = useShikiHighlighter(
code,
"tsx",
{
light: "github-light",
dark: "github-dark",
dim: "github-dark-dimmed",
},
{
defaultColor: "dark",
}
);There are two approaches to make multi-themes reactive to your site's theme:
Set defaultColor="light-dark()" to use CSS's built-in light-dark() function. This automatically switches themes based on the user's color-scheme preference:
// Component
<ShikiHighlighter
language="tsx"
theme={{
light: "github-light",
dark: "github-dark",
}}
defaultColor="light-dark()"
>
{code.trim()}
</ShikiHighlighter>
// Hook
const highlightedCode = useShikiHighlighter(code, "tsx", {
light: "github-light",
dark: "github-dark",
}, {
defaultColor: "light-dark()"
});Ensure your site sets the color-scheme CSS property:
:root {
color-scheme: light dark;
}
/* Or dynamically for class based dark mode */
:root {
color-scheme: light;
}
:root.dark {
color-scheme: dark;
}For broader browser support or more control, add CSS snippets to your site to enable theme switching with media queries or class-based switching. See Shiki's documentation for the required CSS snippets.
Note: The
light-dark()function requires modern browser support. For older browsers, use the manual CSS variables approach.
Custom themes can be passed as a TextMate theme JavaScript object (example).
import tokyoNight from "../styles/tokyo-night.json";
// Component
<ShikiHighlighter language="tsx" theme={tokyoNight}>
{code.trim()}
</ShikiHighlighter>
// Hook
const highlightedCode = useShikiHighlighter(code, "tsx", tokyoNight);When using a fine-grained highlighter via react-shiki/core: pass the theme as a dynamic import to createHighlighterCore so it stays out of the initial chunk, then reference it by its name field:
const highlighter = await createHighlighterCore({
themes: [import("../styles/tokyo-night.json")],
langs: [import("@shikijs/langs/tsx")],
engine: createJavaScriptRegexEngine(),
});
// Component
<ShikiHighlighter highlighter={highlighter} language="tsx" theme="tokyo-night">
{code.trim()}
</ShikiHighlighter>
// Hook
const highlightedCode = useShikiHighlighter(code, "tsx", tokyoNight, {
highlighter,
});Custom languages should be passed as a TextMate grammar JavaScript object (example).
import mcfunction from "../langs/mcfunction.tmLanguage.json";
// Component
<ShikiHighlighter language={mcfunction} theme="github-dark">
{code.trim()}
</ShikiHighlighter>
// Hook
const highlightedCode = useShikiHighlighter(code, mcfunction, "github-dark");Passing grammar objects as props works with the full and web bundles, where react-shiki creates the highlighter and loads them for you. To keep custom grammars out of the main bundle, pass them as dynamic imports via preloadLanguages and reference them by name — see Preloading Languages.
On the core bundle you own the highlighter, so include grammars there as dynamic imports:
const highlighter = await createHighlighterCore({
themes: [import("@shikijs/themes/github-dark")],
langs: [import("../langs/mcfunction.tmLanguage.json")],
engine: createJavaScriptRegexEngine(),
});
// Component
<ShikiHighlighter highlighter={highlighter} language="mcfunction" theme="github-dark">
{code.trim()}
</ShikiHighlighter>
// Hook
const highlightedCode = useShikiHighlighter(code, "mcfunction", "github-dark", {
highlighter,
});If highlighting is dynamic at runtime, preload custom languages.
import mcfunction from "../langs/mcfunction.tmLanguage.json";
import bosque from "../langs/bosque.tmLanguage.json";
// Component
<ShikiHighlighter
language="typescript"
theme="github-dark"
preloadLanguages={[mcfunction, bosque]}
>
{code.trim()}
</ShikiHighlighter>
// Hook
const highlightedCode = useShikiHighlighter(code, "typescript", "github-dark", {
preloadLanguages: [mcfunction, bosque],
});Custom grammars can also be dynamic imports, keeping them out of the main bundle. Reference them by the grammar's name field:
// Module scope: stable identity across renders, fetched on first highlight
const preloadLanguages = [
() => import("../langs/mcfunction.tmLanguage.json"),
() => import("../langs/bosque.tmLanguage.json"),
];
<ShikiHighlighter
language="mcfunction"
theme="github-dark"
preloadLanguages={preloadLanguages}
>
{code.trim()}
</ShikiHighlighter>Important
Define dynamic imports at module scope, preferring the getter form (() => import(...)). A fresh arrow function on every render re-triggers highlighting; bare promises are compared by type, so swapping one at runtime won't be picked up.
Note
Bundled languages are loaded on demand and do not need to be preloaded. preloadLanguages applies to the full and web bundles; with a custom highlighter, load languages in createHighlighterCore instead.
You can define custom aliases for languages using the langAlias option. This is useful when you need to support alternative names for languages:
// Component
<ShikiHighlighter
language="indents"
theme="github-dark"
langAlias={{ indents: "python" }}
>
{code.trim()}
</ShikiHighlighter>
// Hook
const highlightedCode = useShikiHighlighter(code, "indents", "github-dark", {
langAlias: { indents: "python" },
});import { customTransformer } from "../utils/shikiTransformers";
// Component
<ShikiHighlighter language="tsx" transformers={[customTransformer]}>
{code.trim()}
</ShikiHighlighter>
// Hook
const highlightedCode = useShikiHighlighter(code, "tsx", "github-dark", {
transformers: [customTransformer],
});Line numbers are CSS-based and can be customized with CSS variables:
// Component
<ShikiHighlighter
language="javascript"
theme="github-dark"
showLineNumbers
startingLineNumber={0} // default is 1
highlightLineNumbers={[2, 4]}
>
{code}
</ShikiHighlighter>
// Hook (line-number styles inject automatically when enabled)
const highlightedCode = useShikiHighlighter(code, "javascript", "github-dark", {
showLineNumbers: true,
startingLineNumber: 0,
highlightLineNumbers: [2, 4],
});Note
No CSS import is needed: the shared highlighting hook injects line-number and highlight styles automatically when those features are enabled, including when used through the component.
To customize them, override .rs-line-number (line span), .rs-highlighted-line (line span), and .rs-has-line-numbers / .rs-has-highlighted-lines (container code element) in your own CSS.
highlightLineNumbers uses displayed line numbers, so it works with startingLineNumber.
Component styles are embedded in the JS and installed automatically when the component mounts — no CSS import or bundler configuration needed. Injection is scoped to usage: component styles tree-shake out of hook-only bundles entirely, while line-number/highlight styles are installed only when those options are enabled. The complete compiled stylesheet is also exported as react-shiki/css for build-time CSS pipelines or as an externally loaded fallback. Importing it does not disable automatic runtime injection.
Component-internal default classes are namespaced under rs-* and written with zero-specificity :where() selectors, so they can't be clobbered by CSS resets (e.g. Tailwind preflight) regardless of stylesheet load order, while any rule in your own CSS — even a bare element selector — overrides them.
Available CSS variables for customization:
--rs-line-numbers-foreground: rgba(107, 114, 128, 0.5);
--rs-line-numbers-width: 2ch;
--rs-line-numbers-padding-left: 0ch;
--rs-line-numbers-padding-right: 2ch;
--rs-line-numbers-font-size: inherit;
--rs-line-numbers-font-weight: inherit;
--rs-line-numbers-opacity: 1;
--rs-highlighted-line-background: color-mix(in srgb, currentColor 10%, transparent);
--rs-highlighted-line-number-foreground: color-mix(in srgb, currentColor 65%, transparent);With default styles, highlighted-line backgrounds automatically extend into the pre's horizontal padding, reaching the container edges. When styling the pre yourself, highlights cover the code content area.
You can customize them in your own CSS or by using the style prop on the component:
<ShikiHighlighter
language="javascript"
theme="github-dark"
showLineNumbers
style={{
'--rs-line-numbers-foreground': '#60a5fa',
'--rs-line-numbers-width': '3ch'
}}
>
{code}
</ShikiHighlighter>Create a component to handle syntax highlighting:
import ReactMarkdown from "react-markdown";
import ShikiHighlighter, { isInlineCode } from "react-shiki";
const CodeHighlight = ({ className, children, node, ...props }) => {
const code = String(children).trim();
const match = className?.match(/language-(\w+)/);
const language = match ? match[1] : undefined;
const isInline = node ? isInlineCode(node) : undefined;
return !isInline ? (
<ShikiHighlighter language={language} theme="github-dark" {...props}>
{code}
</ShikiHighlighter>
) : (
<code className={className} {...props}>
{code}
</code>
);
};Pass the component to react-markdown as a code component:
<ReactMarkdown
components={{
code: CodeHighlight,
}}
>
{markdown}
</ReactMarkdown>Prior to 9.0.0, react-markdown exposed the inline prop to code
components which helped to determine if code is inline. This functionality was
removed in 9.0.0. For your convenience, react-shiki provides two
ways to replicate this functionality and API.
Method 1: Using the isInlineCode helper:
react-shiki exports isInlineCode which parses the node prop from react-markdown and identifies inline code by checking for the absence of newline characters:
import ShikiHighlighter, { isInlineCode } from "react-shiki";
const CodeHighlight = ({ className, children, node, ...props }) => {
const match = className?.match(/language-(\w+)/);
const language = match ? match[1] : undefined;
const isInline = node ? isInlineCode(node) : undefined;
return !isInline ? (
<ShikiHighlighter language={language} theme="github-dark" {...props}>
{String(children).trim()}
</ShikiHighlighter>
) : (
<code className={className} {...props}>
{children}
</code>
);
};Method 2: Using the rehypeInlineCodeProperty plugin:
react-shiki also exports rehypeInlineCodeProperty, a rehype plugin that
adds an inline prop to react-markdown code components. It works by checking
if <code> is nested within a <pre> tag; if not, it's considered inline code
and the inline prop is set to true.
It's passed as a rehypePlugin to react-markdown:
import ReactMarkdown from "react-markdown";
import { rehypeInlineCodeProperty } from "react-shiki";
<ReactMarkdown
rehypePlugins={[rehypeInlineCodeProperty]}
components={{
code: CodeHighlight,
}}
>
{markdown}
</ReactMarkdown>;Now inline can be accessed as a prop in the code component:
const CodeHighlight = ({
inline,
className,
children,
node,
...props
}: CodeHighlightProps): JSX.Element => {
const match = className?.match(/language-(\w+)/);
const language = match ? match[1] : undefined;
const code = String(children).trim();
return !inline ? (
<ShikiHighlighter language={language} theme="github-dark" {...props}>
{code}
</ShikiHighlighter>
) : (
<code className={className} {...props}>
{code}
</code>
);
};To reduce highlighting work for frequently changing code:
// With the component
<ShikiHighlighter language="tsx" theme="github-dark" delay={150}>
{code.trim()}
</ShikiHighlighter>
// With the hook
const highlightedCode = useShikiHighlighter(code, "tsx", "github-dark", {
delay: 150,
});Made with ❤️ by Bassim (AVGVSTVS96)