Client logic in SSR

Find out how to use client-side methods in SSR environments.

The methods exposed by the Plug only work on the client side. If you try to call them on the server side, you will get the following error:

When calling methods from the useCroct, the operations must be performed within the useEffect hook or client-side callbacks, such as onClick or onChange.

For example, if you want to track a goal when a user visits a pricing page, the following code will throw an error if executed on the server side:

PricingPage.jsx
123456789101112131415
import {useCroct} from '@croct/plug-react';
export function PricingPage() {
const croct = useCroct();
croct.track('goalCompleted', {goalId: 'pricing-page-view'});
return (
<div>
<h1>Pricing</h1>
...
</div>
);
}

To fix this, refactor the tracking operation to run inside a useEffect hook:

PricingPage.jsx
12345677891011121314151617
import {useEffect} from 'react';
import {useCroct} from '@croct/plug-react';
export function PricingPage() {
const croct = useCroct();
croct.track('goalCompleted', {goalId: 'pricing-page-view'});
useEffect(() => {
croct.track('goalCompleted', {goalId: 'pricing-page-view'});
}, [croct]);
return (
<div>
<h1>Pricing</h1>
...
</div>
);
}