React hooks API
@primitree/hooks React providers and hooks.
React 19 hooks for built design tokens and the Figma Variables REST API.
Remarks
TokensProvider reads DTCG token data. FigmaVariablesProvider supplies a file
key and Personal Access Token to the live REST API hooks.
Interfaces
TokensContextValue
Token data and Resolver context controls.
Properties
document
document:
DTCGGroup
The merged document for the active contexts.
flat
flat:
TypedFlatToken[]
Flattened tokens and their effective types in the merged document.
tokensByPath
tokensByPath:
Map<string,DTCGToken>
Token lookup by dot path.
typesByPath
typesByPath:
Map<string,DTCGTokenType|undefined>
Effective token type by dot path.
valuesByPath
valuesByPath:
Map<string,DTCGTokenValue>
Reference-resolved values by dot path.
contexts
contexts:
Record<string,string>
Active context per modifier axis (e.g. { semantic: 'dark' }).
availableContexts
availableContexts:
Record<string,string[]>
Resolver contexts for each axis.
setContext
setContext: (
axis,context) =>void
Switch one axis to a different context.
Parameters
axis
string
context
string
Returns
void
setContexts
setContexts: (
contexts) =>void
Replace the whole context selection at once.
Parameters
contexts
Record<string, string>
Returns
void
TokensProviderProps
Props for TokensProvider.
Properties
tokens
DTCG token documents: a single document, an array (merged in order), or
a file-name map from primitree build. A Resolver needs the map form so
the provider can follow $ref paths.
resolver?
optionalresolver?:ResolverDocument
DTCG Resolver (2025.10) describing modes and contexts. Pass one to let
useTheme switch contexts such as light and dark at runtime.
defaultContexts?
optionaldefaultContexts?:Record<string,string>
Initial context per modifier axis; falls back to resolver defaults.
children
children:
ReactNode
UseThemeResult
Result of useTheme.
Properties
contexts
contexts:
Record<string,string>
Active context per axis, e.g. { semantic: 'dark', density: 'compact' }.
availableContexts
availableContexts:
Record<string,string[]>
Resolver contexts for each axis.
setContext
setContext: (
axis,context) =>void
Switch one axis: setContext('semantic', 'dark').
Parameters
axis
string
context
string
Returns
void
setContexts
setContexts: (
contexts) =>void
Replace the entire selection at once.
Parameters
contexts
Record<string, string>
Returns
void
UseTokenResult
Result of useToken.
Properties
token
token:
DTCGToken|undefined
The token before reference resolution. Its $value can contain a {reference}.
value
value:
DTCGTokenValue|undefined
The value after reference resolution under the active contexts.
type
type:
DTCGTokenType|undefined
Effective type after group inheritance and whole-token alias lookup.
css
css:
string|null
The CSS form of that value, such as 'color(srgb 0.2 0.4 1)' or '8px'.
cssVar
cssVar:
string
The CSS custom property accessor ('var(--semantic-color-bg-brand)').
exists
exists:
boolean
True when the documents contain the token.
FigmaTokenContextType
FigmaVariablesProvider value.
Remarks
Browser code and page scripts can read token. Do not pass a secret to
untrusted client code.
Example
import { useFigmaTokenContext } from '@primitree/hooks';
function TokenStatus() {
const { token, fileKey } = useFigmaTokenContext();
if (!token) return <div>Figma API token missing.</div>;
return <div>
<div>Token configured: {String(Boolean(token))}</div>
<div>File key: {fileKey}</div>
</div>;
}Properties
token
token:
string|null
Figma Personal Access Token, or null. Page scripts can read this value.
fileKey
fileKey:
string|null
Figma file key, or null.
fallbackFile?
optionalfallbackFile?:string|LocalVariablesResponse|PublishedVariablesResponse
Variables response data or JSON used without a live request.
Deprecated
Pass fallback data to FigmaVariablesProvider. Read validated data with useVariables or usePublishedVariables.
swrConfig?
optionalswrConfig?:SWRConfiguration
SWR configuration for hooks under this provider.
FigmaVariablesProviderProps
Props for FigmaVariablesProvider.
Remarks
Browser code and page scripts can read token. Do not include a token in a
public client bundle.
Example
import { FigmaVariablesProvider } from '@primitree/hooks';
<FigmaVariablesProvider token={myToken} fileKey={myFileKey}>
<App />
</FigmaVariablesProvider>Properties
children
children:
ReactNode
The React nodes to render inside the provider.
token
token:
string|null
Figma Personal Access Token, or null. Page scripts can read this value.
fileKey
fileKey:
string|null
Figma file key, or null.
fallbackFile?
optionalfallbackFile?:string|LocalVariablesResponse|PublishedVariablesResponse
Variables response data or JSON used without a live request.
fallbackKind?
optionalfallbackKind?:FallbackDataKind
Response kind for fallback data whose shape does not reveal the kind, such as a response with empty collection and variable maps.
swrConfig?
optionalswrConfig?:SWRConfiguration
SWR configuration for caching, revalidation, and error handling.
Example
<FigmaVariablesProvider
token={token}
fileKey={fileKey}
swrConfig={{
revalidateOnFocus: false,
dedupingInterval: 5000,
errorRetryCount: 3,
}}
>
<App />
</FigmaVariablesProvider>UpdateVariableArgs
Arguments passed to useUpdateVariable().mutate.
Remarks
variableId identifies the record. payload contains the fields to change.
Example
import type { UpdateVariableArgs } from '@primitree/hooks';
const args: UpdateVariableArgs = {
variableId: 'VariableID:123:456',
payload: { name: 'Updated Name', description: 'Updated description' }
};
mutate(args)Properties
variableId
variableId:
string
The unique Figma variable ID from variable metadata or Figma plugin developer tools.
payload
payload:
UpdateVariablePayload
The payload object with one or more variable properties to update (e.g., name, description, valuesByMode).
UseVariableModesResult
Variable modes and ID-keyed lookup maps.
Remarks
useVariableModes builds these values from local collection data.
Example
import { useVariableModes } from '@primitree/hooks';
function ThemeSwitcher() {
const { modes, modesById } = useVariableModes();
// Build UI for switching themes based on mode names
return (
<select>
{modes.map(mode => (
<option key={mode.modeId} value={mode.modeId}>{mode.name}</option>
))}
</select>
);
}Properties
modes
modes:
VariableMode[]
Flat array of all VariableMode objects in the file.
modesByCollectionId
modesByCollectionId:
Record<string,VariableMode[]>
Lookup map of collection IDs to arrays of VariableMode objects (for grouping modes by collection).
modesById
modesById:
Record<string,VariableMode>
Lookup map of mode IDs to VariableMode objects (for fast direct access).
Functions
FigmaVariablesProvider()
FigmaVariablesProvider(
__namedParameters):Element
Provide a Figma file key, token, and fallback data to live API hooks.
Parameters
__namedParameters
Returns
Element
Remarks
Browser code and page scripts can read a token passed here. Do not expose a token to untrusted client code or include it in a public browser bundle. The provider parses and classifies fallback JSON during render.
Example
import { FigmaVariablesProvider } from '@primitree/hooks'
function App({ token }: { token: string }) {
return (
<FigmaVariablesProvider token={token} fileKey="AbC123">
<MyDashboard />
</FigmaVariablesProvider>
);
}useFigmaTokenContext()
useFigmaTokenContext():
FigmaTokenContextType
Read the value from the nearest FigmaVariablesProvider.
Returns
Throws
Error outside a FigmaVariablesProvider.
useBulkUpdateVariables()
useBulkUpdateVariables():
MutationResult<unknown,BulkUpdatePayload>
Create, update, or delete Figma collections, modes, and variables in one request.
Returns
MutationResult<unknown, BulkUpdatePayload>
Mutation state and a mutate function.
Remarks
mutate accepts a BulkUpdatePayload. It returns the response or
undefined after storing a request failure in error.
Example
import { useBulkUpdateVariables } from '@primitree/hooks';
function BulkUpdateButton() {
const { mutate, isLoading, isError, error } = useBulkUpdateVariables();
const handleBulkUpdate = async () => {
const result = await mutate({
variables: [{ action: 'UPDATE', id: 'VariableId:123', name: 'new-name' }],
});
if (result) {
console.log('Bulk update successful');
}
};
if (isLoading) return <div>Updating...</div>;
if (isError) return <div>Error: {error?.message}</div>;
return <button onClick={handleBulkUpdate}>Bulk Update</button>;
}useCollectionById()
useCollectionById(
collectionId):FigmaCollection|undefined
Select a Figma variable collection by ID.
Parameters
collectionId
string
The ID of the collection to retrieve.
Returns
FigmaCollection | undefined
The collection, or undefined for an unknown ID.
Remarks
The hook reads collection data from useVariableCollections.
Example
import { useCollectionById } from '@primitree/hooks';
function CollectionDetails({ collectionId }: { collectionId: string }) {
const collection = useCollectionById(collectionId);
if (!collection) return <div>Collection not found</div>;
return <div>
<h2>{collection.name}</h2>
<p>Variables: {collection.variableIds.length}</p>
</div>;
}useCreateVariable()
useCreateVariable():
MutationResult<unknown,CreateVariablePayload>
Create a Figma variable in the provider's file.
Returns
MutationResult<unknown, CreateVariablePayload>
Mutation state and a mutate function.
Remarks
mutate accepts a CreateVariablePayload. It returns the response or
undefined after storing a request failure in error.
Example
import { useCreateVariable } from '@primitree/hooks';
function CreateVariableButton() {
const { mutate, isLoading, isError, error } = useCreateVariable();
const handleCreate = async () => {
const result = await mutate({
name: 'new-variable',
variableCollectionId: 'VariableCollectionId:1:1',
resolvedType: 'COLOR'
});
if (result) {
console.log('Created variable:', result);
}
};
if (isLoading) return <div>Creating...</div>;
if (isError) return <div>Error: {error?.message}</div>;
return <button onClick={handleCreate}>Create Variable</button>;
}useDeleteVariable()
useDeleteVariable():
MutationResult<unknown,string>
Delete a Figma variable from the provider's file.
Returns
MutationResult<unknown, string>
Mutation state and a mutate function.
Remarks
mutate accepts a variable ID. It returns the response or undefined
after storing a request failure in error.
Example
import { useDeleteVariable } from '@primitree/hooks';
function DeleteVariableButton({ id }: { id: string }) {
const { mutate, isLoading, isError, error } = useDeleteVariable();
const onDelete = async () => {
const result = await mutate(id);
if (result) {
console.log('Deleted variable');
}
};
if (isLoading) return <div>Deleting...</div>;
if (isError) return <div>Error: {error?.message}</div>;
return <button onClick={onDelete}>Delete Variable</button>;
}useFigmaToken()
useFigmaToken():
string|null
Read the Figma Personal Access Token from context.
Returns
string | null
Remarks
Browser code and page scripts can read the returned token. Do not expose it to untrusted client code or use its presence as route authorization.
Example
import { useFigmaToken } from '@primitree/hooks';
function AuthStatus() {
const token = useFigmaToken();
if (!token) return <div>Please provide a Figma API token.</div>;
return <div>Token available.</div>;
}useInvalidateVariables()
useInvalidateVariables():
object
Return functions that invalidate or revalidate Figma Variables SWR entries.
Returns
Object with invalidate and revalidate functions.
invalidate
invalidate: () =>
void
Marks this provider's live and fallback cache keys stale. SWR refetches them on the next read.
Returns
void
revalidate
revalidate: () =>
void
Requests a fresh value for each live and fallback cache key.
Returns
void
Remarks
Both functions target live API data and validated fallback data for the current provider.
Example
import { useInvalidateVariables, useUpdateVariable } from '@primitree/hooks';
function UpdateButton() {
const { mutate } = useUpdateVariable();
const { invalidate } = useInvalidateVariables();
const handleUpdate = async () => {
await mutate({ variableId: 'id', payload: { name: 'New Name' } });
invalidate(); // Refetch all variable queries
};
}useModesByCollection()
useModesByCollection(
collectionId):VariableMode[]
Select modes for a Figma variable collection.
Parameters
collectionId
string
The ID of the collection to get modes for.
Returns
The collection modes, or an empty array for an unknown collection.
Remarks
The hook returns an empty array for an unknown collection or one without loaded modes.
Example
import { useModesByCollection } from '@primitree/hooks';
function CollectionModes({ collectionId }: { collectionId: string }) {
const modes = useModesByCollection(collectionId);
if (!modes.length) return <div>No modes found</div>;
return (
<ul>
{modes.map(mode => (
<li key={mode.modeId}>{mode.name}</li>
))}
</ul>
);
}usePublishedVariables()
usePublishedVariables():
SWRResponse<PublishedVariablesResponse,any,SWRConfiguration<PublishedVariablesResponse,any,BareFetcher<PublishedVariablesResponse>> |undefined>
Read published Figma variables for the provider's file.
Returns
SWRResponse<PublishedVariablesResponse, any, SWRConfiguration<PublishedVariablesResponse, any, BareFetcher<PublishedVariablesResponse>> | undefined>
SWR response object with data, error, isLoading, and isValidating.
Remarks
The hook reads validated published fallback data without a request. Without that fallback, SWR fetches the published variables endpoint when the provider has a file key and token.
Example
import { usePublishedVariables } from '@primitree/hooks';
function LibraryTokens() {
const { data, isLoading, error } = usePublishedVariables();
if (isLoading) return <div>Loading published variables...</div>;
if (error) return <div>Error: {error.message}</div>;
const variables = Object.values(data?.meta.variables ?? {});
return <ul>{variables.map(v => <li key={v.id}>{v.name}</li>)}</ul>;
}useUpdateVariable()
useUpdateVariable():
MutationResult<unknown, {variableId:string;payload:UpdateVariablePayload; }>
Update a Figma variable in the provider's file.
Returns
MutationResult<unknown, { variableId: string; payload: UpdateVariablePayload; }>
Mutation state and a mutate function.
Remarks
mutate accepts a variable ID and UpdateVariablePayload. It returns
the response or undefined after storing a request failure in error.
Example
import { useUpdateVariable } from '@primitree/hooks';
function UpdateVariableButton({ id }: { id: string }) {
const { mutate, isLoading, isError, error } = useUpdateVariable();
const onUpdate = async () => {
const result = await mutate({ variableId: id, payload: { name: 'new-name' } });
if (result) {
console.log('Updated variable');
}
};
if (isLoading) return <div>Updating...</div>;
if (isError) return <div>Error: {error?.message}</div>;
return <button onClick={onUpdate}>Update Variable</button>;
}useVariableById()
useVariableById(
variableId):FigmaVariable|undefined
Select a Figma variable by ID.
Parameters
variableId
string
The ID of the variable to retrieve.
Returns
FigmaVariable | undefined
The variable, or undefined for an unknown ID.
Remarks
The hook reads local data from useVariables.
Example
import { useVariableById } from '@primitree/hooks';
function VariableDetails({ variableId }: { variableId: string }) {
const variable = useVariableById(variableId);
if (!variable) return <div>Variable not found</div>;
return <div>
<h2>{variable.name}</h2>
<p>Type: {variable.resolvedType}</p>
</div>;
}useVariableCollections()
useVariableCollections():
object
Read local variable collections as an array and an ID-keyed map.
Returns
object
collections
collections:
FigmaCollection[]
collectionsById
collectionsById:
Record<string,FigmaCollection>
Remarks
The hook derives both values from useVariables.
Example
import { useVariableCollections } from '@primitree/hooks';
function CollectionList() {
const { collections } = useVariableCollections();
if (!collections.length) return <div>No collections found.</div>;
return (
<ul>
{collections.map(col => (
<li key={col.id}>{col.name}</li>
))}
</ul>
);
}useVariableModes()
useVariableModes():
UseVariableModesResult
Read local variable modes as arrays and ID-keyed maps.
Returns
Remarks
The hook groups modes by collection ID and indexes them by mode ID.
Example
import { useVariableModes } from '@primitree/hooks';
function ModeList() {
const { modes } = useVariableModes();
if (!modes.length) return <div>No modes found.</div>;
return (
<ul>
{modes.map(mode => (
<li key={mode.modeId}>{mode.name}</li>
))}
</ul>
);
}useVariables()
useVariables():
SWRResponse<LocalVariablesResponse,any,SWRConfiguration<LocalVariablesResponse,any,BareFetcher<LocalVariablesResponse>> |undefined>
Read local Figma variables for the provider's file.
Returns
SWRResponse<LocalVariablesResponse, any, SWRConfiguration<LocalVariablesResponse, any, BareFetcher<LocalVariablesResponse>> | undefined>
SWR response object with data, error, isLoading, and isValidating.
Remarks
The hook reads validated local fallback data without a request. Without that fallback, SWR fetches the local variables endpoint when the provider has a file key and token.
TokensProvider()
TokensProvider(
__namedParameters):Element
Provide DTCG token files and a Resolver to the local-token hooks: useToken, useTokens, useTheme.
Parameters
__namedParameters
Returns
Element
Remarks
The provider accepts output from primitree build or other DTCG documents.
It reads local data and does not require a Figma token.
Example
import { TokensProvider, useToken, useTheme } from '@primitree/hooks'
import primitives from './tokens/primitives.tokens.json'
import semantic from './tokens/semantic.tokens.json'
import semanticDark from './tokens/semantic.dark.tokens.json'
import resolver from './tokens/tokens.resolver.json'
<TokensProvider
tokens={{
'primitives.tokens.json': primitives,
'semantic.tokens.json': semantic,
'semantic.dark.tokens.json': semanticDark,
}}
resolver={resolver}>
<App />
</TokensProvider>useTheme()
useTheme():
UseThemeResult
Read and switch resolver contexts (Figma modes) at runtime.
Returns
Remarks
primitree build writes the DTCG Resolver that supplies axes and context
names. For a Figma collection named "Theme" with Light and Dark modes, call
setContext('theme', 'dark').
Example
const { contexts, availableContexts, setContext } = useTheme()
<button onClick={() => setContext('semantic', contexts.semantic === 'dark' ? 'light' : 'dark')}>
Toggle theme
</button>useToken()
useToken(
path):UseTokenResult
Read one design token by dot path from the nearest TokensProvider.
Parameters
path
string
Dot-joined token path, e.g. 'semantic.color.bg.brand'.
Returns
Remarks
Values resolve through DTCG references under the active contexts, so switching a theme axis via useTheme re-renders consumers with the new value.
Example
const brand = useToken('semantic.color.bg.brand')
return <div style={{ background: brand.css ?? undefined }} />useTokens()
useTokens():
TokensContextValue
Read token data from the nearest TokensProvider: the merged document, flattened tokens, resolved values, and context controls.
Returns
Throws
Error outside a TokensProvider.
Example
const { flat, valuesByPath } = useTokens()
const colors = flat.filter(t => t.type === 'color')References
ResolvedType
Re-exports ResolvedType
VariableScope
Re-exports VariableScope
Color
Re-exports Color
VariableAlias
Re-exports VariableAlias
VariableValue
Re-exports VariableValue
FigmaVariable
Re-exports FigmaVariable
VariableMode
Re-exports VariableMode
FigmaCollection
Re-exports FigmaCollection
LocalVariablesResponse
Re-exports LocalVariablesResponse
PublishedVariable
Re-exports PublishedVariable
PublishedVariableCollection
Re-exports PublishedVariableCollection
PublishedVariablesResponse
Re-exports PublishedVariablesResponse
FigmaError
Re-exports FigmaError
FigmaApiError
Re-exports FigmaApiError
CreateVariablePayload
Re-exports CreateVariablePayload
UpdateVariablePayload
Re-exports UpdateVariablePayload
VariableAction
Re-exports VariableAction
VariableCollectionChange
Re-exports VariableCollectionChange
VariableModeChange
Re-exports VariableModeChange
VariableChange
Re-exports VariableChange
VariableMutationValue
Re-exports VariableMutationValue
VariableModeValue
Re-exports VariableModeValue
BulkUpdatePayload
Re-exports BulkUpdatePayload
BulkUpdateResponse
Re-exports BulkUpdateResponse
MutationState
Re-exports MutationState
MutationOptions
Re-exports MutationOptions
MutationResult
Re-exports MutationResult
filterVariables
Re-exports filterVariables
withRetry
Re-exports withRetry
redactToken
Re-exports redactToken
isFigmaApiError
Re-exports isFigmaApiError
getErrorStatus
Re-exports getErrorStatus
getErrorMessage
Re-exports getErrorMessage
hasErrorStatus
Re-exports hasErrorStatus
isRateLimited
Re-exports isRateLimited
getRetryAfter
Re-exports getRetryAfter
isLocalVariablesResponse
Re-exports isLocalVariablesResponse
isPublishedVariablesResponse
Re-exports isPublishedVariablesResponse
validateFallbackData
Re-exports validateFallbackData