React
Vite, React Router and other React apps
For a React app, add the <Analytics /> component from @viakite/sdk/react once, at the top of your app. It works with Vite, Create React App, React Router and any other router that uses the browser's history. Using Next.js? See Next.js.
Install
1npm install @viakite/sdk
1pnpm add @viakite/sdk
1yarn add @viakite/sdk
It needs React 18 or later. React is a peer dependency, so the package adds no second copy.
Add the component
Put it once in your root component, next to your router:
1import { Analytics } from "@viakite/sdk/react";23export default function App() {4return (5<>6{/* your routes */}7<Analytics project="pk_live_us_…" />8</>9);10}
It renders nothing. After it mounts, in the browser, it calls init() with its props: the first page view is sent, and every route change after it counts as a page view.
How it behaves
- Once per page load. A re-render doesn't start it again, and props that change after it mounts are ignored, like the script tag's attributes.
- Strict mode is fine. React runs effects twice in development; the second
init()call does nothing. - Server rendering is fine. On the server it renders nothing and doesn't call
init(). - Route changes are followed through
history.pushState,replaceStateandpopstate: one page view per new path, none when only the query changes.
Send events
Import track, identify and reset from @viakite/sdk anywhere:
1import { track } from "@viakite/sdk";23export function SignupButton() {4return <button onClick={() => track("Signup", { plan: "pro" })}>Start free</button>;5}
Calls made before <Analytics /> has mounted, such as from a child component's effect (React runs a child's effects before its parent's), are kept and sent once it does.
Tie events to the signed-in user:
1import { useEffect } from "react";2import { identify, reset } from "@viakite/sdk";34export function Identify({ userId }: { userId?: string }) {5useEffect(() => {6if (userId) identify(userId);7else reset();8}, [userId]);9return null;10}
Options
Every option of init() is a prop:
1<Analytics project={import.meta.env.VITE_VIAKITE_KEY} title hash={false} params={["plan"]} outbound={false} />
Nothing is sent from localhost. While you work, add debug to see events in the console without sending, or localhost to send them. For a hash router (/#/about), add hash. For a router that doesn't use the history API, set autoPageviews={false} and call pageview() on each route change. All props: Options.