React
Run a measurement from a React component with the useNeccessoryMeasurement hook.
useNeccessoryMeasurement runs the same measurement as createMeasurement(), with refs
instead of elements and state instead of callbacks. It requires React 18 or later.
import { useNeccessoryMeasurement } from '@neccessory/web-sdk/react';
const m = useNeccessoryMeasurement(creds, options);creds is { keyId, secret } in on-device mode, where secret is optional. Pass
undefined in cloud mode.
Cloud mode
Your backend creates the session as shown in the Quickstart.
import { useEffect, useState } from 'react';
import { useNeccessoryMeasurement } from '@neccessory/web-sdk/react';
const hiddenVideo = { position: 'fixed', width: 1, height: 1, opacity: 0, pointerEvents: 'none' };
const HINT_TEXT = {
faceTooSmall: 'Move closer to the camera',
tooDark: 'Find more light',
tooBright: 'Move out of direct light',
unstable: 'Hold still',
lowSignal: 'Keep your face in view and hold still',
};
export function CloudMeasurement() {
const [session, setSession] = useState();
const m = useNeccessoryMeasurement(undefined, { mode: 'cloud', session });
useEffect(() => {
if (session) m.start();
}, [session]);
async function begin() {
const response = await fetch('/api/measurement-session', { method: 'POST' });
if (response.ok) setSession(await response.json());
}
const busy = m.phase === 'loading' || m.phase === 'running';
return (
<div>
<video ref={m.videoRef} playsInline muted style={hiddenVideo} />
<canvas ref={m.previewRef} style={{ width: '100%' }} />
{m.phase === 'running' && <p>{m.realtime.heartRate ?? '--'} bpm</p>}
{m.coach && <p>{HINT_TEXT[m.coach]}</p>}
{m.stage === 'processing' && <p>Calculating results…</p>}
{m.phase === 'done' && <p>Heart rate: {m.result.cardiac.heartRate.value ?? '--'} bpm</p>}
{m.phase === 'error' && <p>Measurement failed: {m.error.code}</p>}
<button onClick={begin} disabled={busy}>Start</button>
</div>
);
}start() uses the options from the render it belongs to. Keep the session in state and call
start() from an effect, as above. Calling it right after setSession() would start with
the previous session.
The measurement ends at the session's duration and phase becomes 'done'. Each run
needs a new session — pressing Start again requests one.
On-device mode
On-device mode has no automatic end: call stop() when your timer runs out. stop()
computes the result, and phase becomes 'done'.
import { useEffect, useState } from 'react';
import { prefetchMeasurement, useNeccessoryMeasurement } from '@neccessory/web-sdk/react';
const DURATION_MS = 45_000;
const hiddenVideo = { position: 'fixed', width: 1, height: 1, opacity: 0, pointerEvents: 'none' };
export function OnDeviceMeasurement() {
const [modelGrant, setModelGrant] = useState();
const m = useNeccessoryMeasurement({ keyId: 'nk_live_…' }, { mode: 'on-device', modelGrant });
useEffect(() => {
prefetchMeasurement();
fetch('/api/model-grant', { method: 'POST' })
.then((response) => response.json())
.then(({ grant }) => setModelGrant(grant));
}, []);
useEffect(() => {
if (m.phase !== 'running') return;
const timer = setTimeout(m.stop, DURATION_MS);
return () => clearTimeout(timer);
}, [m.phase]);
useEffect(() => {
if (!m.submitInput) return;
fetch('/api/measurements', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(m.submitInput),
});
}, [m.result]);
const busy = m.phase === 'loading' || m.phase === 'running';
return (
<div>
<video ref={m.videoRef} playsInline muted style={hiddenVideo} />
<canvas ref={m.previewRef} style={{ width: '100%' }} />
{m.phase === 'running' && <p>{m.realtime.heartRate ?? '--'} bpm</p>}
{m.phase === 'error' && <p>Measurement failed: {m.error.code}</p>}
<button onClick={() => m.start()} disabled={!modelGrant || busy}>Start</button>
</div>
);
}submitInput is the result in the format of POST /sdk/v1/measurements. Your backend
stores it with signAndSubmit() — see the Quickstart. A model
grant is valid for 15 minutes; mint a new one for measurements started later.
Options
The second argument accepts these options:
| Option | Type | Default | Description |
|---|---|---|---|
mode | 'on-device' | 'cloud' | 'on-device' | Processing mode. |
modelGrant | string | — | On-device. Grant from POST /sdk/v1/models/grant. |
session | CloudSession | — | Cloud. The whole data object from POST /sdk/v1/cloud/sessions. |
sessionToken, sessionId, wsUrl | string | from session | Cloud. Override individual session fields. |
delivery | 'stream' | 'batch' | 'auto' | 'auto' | Cloud. How measurement data reaches Neccessory cloud — see Configuration. |
assetOrigin | string | https://neccessory.com | Host of the SDK runtime files. Set https://neccessory.com explicitly on localhost. |
apiOrigin | string | https://neccessory.com | Cloud. Change only if Neccessory gave you a dedicated host. |
The hook always uses the session's duration and the defaults for aux, mediapipeBase and
modelBasePath. To set them, use createMeasurement().
Return value
| Field | Type | Description |
|---|---|---|
phase | 'idle' | 'loading' | 'running' | 'done' | 'error' | Lifecycle state — see below. |
stage | MeasurementStage | null | Latest progress stage — see Callbacks & errors. null before start(). |
coach | CoachReason | null | Cloud. Current hint for the user, or null. |
deliveryFallback | { reason, source } | null | Cloud with delivery: 'auto'. Set when the SDK finishes the measurement by upload. |
error | { code, message } | null | Last error. |
realtime | { heartRate, quality } | Latest live update. Before the first one: heartRate: null, quality: { level: 'poor', score: null }. |
result | MeasurementResult | null | Final measurement result. |
submitInput | MeasurementInput | null | result as the request body of POST /sdk/v1/measurements. |
videoRef | ref | Attach to a <video> element. Required. |
previewRef | ref | Attach to a <canvas> for the camera preview. Optional. |
overlayRef | ref | Attach to a <canvas> for the face frame. Optional. |
start() | () => Promise<void> | Resets the state and starts a new measurement. |
stop() | () => void | Ends the measurement and releases the camera. |
| Phase | Meaning |
|---|---|
'idle' | Before start(), or after stop() when there is no result. |
'loading' | The camera and the SDK are starting. |
'running' | The measurement is in progress. In cloud mode, this includes uploading and processing after stop(). |
'done' | result is set. |
'error' | error is set. |
Behavior
- Render the video element first.
videoRefmust be attached when you callstart(), otherwiseerror.codeisno_video. The canvases can mount later — the hook picks them up when they appear. - Unmount cleans up. Unmounting the component stops the measurement and releases the camera.
- Cloud duration comes from the session. Set
durationSecwhen your backend creates the session. - Stopping in cloud mode. After
stop(),phasestays'running'while the SDK uploads and processes the data, then becomes'done'when the result arrives.