@numinstante/patience-engine-react
v0.1.6
Published
[](https://www.npmjs.com/package/@numinstante/patience-engine-react) [](https://trav
Readme
@numinstante/patience-engine-react
@numinstante/patience-engine-react is the official tracking library for the Patience Engine for React applications. It provides a simple and idiomatic way to collect user behavior events, using FingerprintJS for anonymous identification.
Table of Contents
- Installation
- Quick Start
- Architecture & Concepts
- API Reference
- Publishing a Scoped Package
- Contributing
- License
Installation
To install the library and its main dependency, FingerprintJS:
npm install @numinstante/patience-engine-react @fingerprintjs/fingerprintjsOptional Dependencies
Depending on your routing library, you may need to install additional dependencies for page tracking:
For React Router applications:
npm install react-router-domFor Next.js applications:
npm install next
These dependencies are optional and only required if you plan to use the corresponding page tracking components. The library is designed to work with either routing system without requiring both dependencies to be installed.
Note: The library will automatically detect which routing library is available in your project. If you're using Next.js without react-router-dom installed, the library will still work correctly and will not throw any errors related to missing dependencies.
Quick Start
To start using the library, wrap your main application with the PatienceProvider and use the usePatience hook in any child component.
- Set up the Provider in your
main.tsxorindex.tsx:
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { PatienceProvider } from '@numinstante/patience-engine-react';
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<PatienceProvider
apiKey="YOUR_PUBLIC_API_KEY"
endpoint="[https://api.patience-engine.com/events](https://api.patience-engine.com/events)"
>
<App />
</PatienceProvider>
</React.StrictMode>
);- Use the Hook in a Component:
import { usePatience } from '@numinstante/patience-engine-react';
function MyAwesomeComponent() {
const { track, visitorId, identify } = usePatience();
const handleButtonClick = () => {
// Sends a track event with a custom payload
track('button_signup_clicked', { variant: 'primary', plan: 'free' });
};
return (
<div>
<p>Your anonymous visitor ID is: {visitorId || 'Loading...'}</p>
<button onClick={handleButtonClick}>Sign Up</button>
</div>
);
}Architecture & Concepts
The library is designed to be efficient and easy to use, following the best practices of the React ecosystem. The architecture is based on three pillars: the Provider, the Context, and the Hook.
PatienceProvider: This is the brain of the library. It wraps your application and is responsible for all the initialization logic (loading FingerprintJS, getting the visitorId, configuring the API) only once.PatienceContext: Acts as an internal transport channel, making the state and functions from the provider available to the entire component tree efficiently.usePatience(): This is the public interface and the correct way to access the library's functionality from within your components.
This structure ensures that the heavy initialization logic runs only once, while access to data and functions is lightweight and performant.
API Reference
Page Tracking Components
The library provides components for automatic page view tracking in different routing libraries:
<ReactRouterPageTracker />
This component automatically tracks page views in applications using React Router v6+.
Installation:
# React Router is an optional peer dependency
npm install react-router-domUsage:
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import { ReactRouterPageTracker } from '@numinstante/patience-engine-react';
function App() {
return (
<BrowserRouter>
<ReactRouterPageTracker />
<Routes>
{/* Your routes */}
</Routes>
</BrowserRouter>
);
}Fallback Behavior:
If you import ReactRouterPageTracker in a project where react-router-dom is not installed, the library will provide a fallback component that logs a warning to the console but doesn't break your application. This is useful in environments where you might be using the library with Next.js instead of React Router.
<NextJsPageTracker />
This component automatically tracks page views in applications using Next.js 13+ App Router.
Installation:
# Next.js is an optional peer dependency
npm install nextUsage:
// app/layout.tsx
import { NextJsPageTracker } from '@numinstante/patience-engine-react';
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<NextJsPageTracker />
{children}
</body>
</html>
);
}<PatienceProvider />
Props that the component accepts:
| Prop | Type | Required | Description | |----------|-----------|----------|-------------------------------------------------| | apiKey | string | Yes | Your public API key from the Patience Engine. | | endpoint | string | Yes | The full URL of your event ingestion endpoint. | | children | ReactNode | Yes | The child components of your React application. | | options | Object | No | Optional configuration options (see below). |
Options Object
| Option | Type | Default | Description | |----------|---------|----------------|-------------------------------------------------| | disabled | boolean | false | If true, tracking will be disabled. | | cookie | Object | (see below) | Configuration for the visitorId cookie. |
Cookie Object
| Option | Type | Default | Description | |---------|--------|------------------|-----------------------------------------| | name | string | "__patience_vid" | The name of the cookie. | | expires | number | 365 | The cookie's expiration period in days. | | domain | string | undefined | The domain to set the cookie on. |
usePatience()
Hook that returns an object with the following properties:
| Property | Type | Description | |-----------|----------|------------------------------------------------------------| | visitorId | string | The unique identifier for the anonymous visitor. | | disabled | boolean | Indicates whether tracking is disabled. | | track | function | Function to send custom events to the Patience Engine. | | identify | function | Function to associate an anonymous visitor with a user ID. | | reset | function | Function to clear user identification (logout). |
track(eventName, payload)
Sends a custom event to the Patience Engine.
| Parameter | Type | Required | Description | |-----------|--------|----------|--------------------------------------------------| | eventName | string | Yes | A string that identifies the event. | | payload | object | No | A JSON-serializable object with custom data. |
Example:
const { track } = usePatience();
// Track a button click with additional data
track('button_clicked', {
buttonId: 'signup',
variant: 'primary',
position: 'header'
});identify(userId, traits)
Associates the current anonymous visitor with a permanent user ID and records their traits.
| Parameter | Type | Required | Description | |-----------|--------|----------|------------------------------------------------------------| | userId | string | Yes | The permanent, unique identifier for the user. | | traits | object | No | A JSON-serializable object with user attributes. |
Example:
const { identify } = usePatience();
// After user login, associate the anonymous visitor with the authenticated user
identify('user_123', {
name: 'Jane Doe',
email: '[email protected]',
plan: 'premium',
signupDate: '2023-01-15'
});reset()
Clears the currently identified user's session, reverting the library's tracking state back to being purely anonymous without losing the persistent anonymous visitorId.
This function takes no parameters and returns void.
Example:
const { reset } = usePatience();
// When user logs out, clear their identification
function handleLogout() {
// First, handle your application's logout logic
await api.logout();
// Then reset the Patience Engine identification
reset();
// Finally, redirect the user
navigate('/login');
}Publishing a Scoped Package
This package is published under the @numinstante scope on NPM. To publish a new version, follow these steps:
Ensure you have permission to publish packages under the
@numinstanteorganization/scope on NPM.Authenticate with your NPM account using
npm login.Make sure your local
mainbranch is up-to-date with the remote repository and all tests are passing:git pull origin main npm run lintDetermine the type of release based on the changes made since the last release:
- Patch: Bug fixes and small changes that don't affect the API
- Minor: New features that don't break backward compatibility
- Major: Breaking changes
Run one of the following commands to increment the version number:
# For bug fixes and small changes npm run release:patch # For new features that don't break backward compatibility npm run release:minor # For breaking changes npm run release:majorThis will update the version in package.json and create a Git tag.
Build the project:
npm run buildPerform a dry run to verify which files will be included in the package:
npm run publish:dry-runIf the files look correct, publish the package to NPM:
npm run publish:publicPush the new commit and tag to the remote Git repository:
git push git push --tags
If the files don't look correct during the dry run, you can revert the version change:
git reset --hard HEAD~1
git tag -d v<version>The release process will:
- Increment the version number in
package.jsonaccording to semantic versioning - Create a Git tag for the new version
- Build the distributable files
- Publish the package to NPM with public access
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
MIT
