Skip to main content

useAnalytics

The useAnalytics hook can be used to access a Provider's track function. It's useful in situations where analytics isn't provided by default such as mounting a component, other lifecycle methods, or with custom behavior.

The following example shows how to use the hook to track when a component mounts.

In these examples TrackableFeature is a component internal to this documentation that provides an analytics Provider.

Result
Loading...
Live Editor
const TrackableFeature = (props) => {
	const [trackedPaths, setTrackedPaths] = useState([]);

	return (
		<>
			<Provider
				value="Provider"
				onTrack={(trackedProperties, action) => {
					setTrackedPaths((currentTrackedPaths) => [a
						{ path: trackedProperties.path, action },
						...currentTrackedPaths,
					]);
				}}
			>
				{props.children}
			</Provider>
			<hr />

			{trackedPaths && (
				<section>
					Tracked Properties & Actions:
					<pre>{JSON.stringify(trackedPaths, null, 2)}</pre>
				</section>
			)}
		</>
	);
};

const MyCustomComponent = (props) => {
	const [track] = useAnalytics(props);

	useEffect(() => {
		track('MyCustomComponent', { type: 'MY_CUSTOM_COMPONENT_MOUNT', payload: 'mount' });
	}, []); // no dependencies, only run this function once.

	return <div>{props.children}</div>;
};

render(
	<TrackableFeature>
		<MyCustomComponent>👻</MyCustomComponent>
	</TrackableFeature>,
);

Tracking show/hide in a Modal

Result
Loading...
Live Editor
const TrackableFeature = (props) => {
	const [trackedPaths, setTrackedPaths] = useState([]);

	return (
		<>
			<Provider
				value="Provider"
				onTrack={(trackedProperties, action) => {
					setTrackedPaths((currentTrackedPaths) => [
						{ path: trackedProperties.path, action },
						...currentTrackedPaths,
					]);
				}}
			>
				{props.children}
			</Provider>
			<hr />

			{trackedPaths && (
				<section>
					Tracked Properties & Actions:
					<pre>{JSON.stringify(trackedPaths, null, 2)}</pre>
				</section>
			)}
		</>
	);
};

const MyCustomModal = (props) => {
	const [track] = useAnalytics(props);
	const { show, onHide } = props;

	useEffect(() => {
		if (show) {
			track('MyCustomModal', { type: 'MY_CUSTOM_MODAL_SHOW', payload: 'show' });
		}
	}, [show]);

	const handleHide = () => {
		track('MyCustomModal', { type: 'MY_CUSTOM_MODAL_HIDE', payload: 'hide' });
		onHide();
	};

	return (
		<Modal show={show} onHide={handleHide} title="Reptiles">
			<Modal.Body>🦎 🐍</Modal.Body>
		</Modal>
	);
};

const MyCustomModalContainer = () => {
	const [show, setShow] = useState(false);

	const handleOnClick = () => {
		setShow(true);
	};

	const handleHide = () => {
		setShow(false);
	};

	return (
		<TrackableFeature>
			<MyCustomModal show={show} onHide={handleHide} />

			<Button onClick={handleOnClick}>Show Modal</Button>
		</TrackableFeature>
	);
};

render(<MyCustomModalContainer />);