viakite
Dashboard

SDKs/Frameworks/React

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

terminal
1npm install @viakite/sdk
terminal
1pnpm add @viakite/sdk
terminal
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:

src/App.tsx
1import { Analytics } from "@viakite/sdk/react";
2
3export default function App() {
4 return (
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, replaceState and popstate: one page view per new path, none when only the query changes.

Send events

Import track, identify and reset from @viakite/sdk anywhere:

src/SignupButton.tsx
1import { track } from "@viakite/sdk";
2
3export function SignupButton() {
4 return <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:

src/Identify.tsx
1import { useEffect } from "react";
2import { identify, reset } from "@viakite/sdk";
3
4export function Identify({ userId }: { userId?: string }) {
5 useEffect(() => {
6 if (userId) identify(userId);
7 else reset();
8 }, [userId]);
9 return null;
10}

Options

Every option of init() is a prop:

src/App.tsx
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.

Next steps