@shish2k/react-use-servertime
TypeScript icon, indicating that this package has built-in type declarations

0.0.3 • Public • Published

React useServerTime

A hook which allows multiple clients to keep their clocks in-sync with reasonable precision, eg

import { useServerTime } from "@shish2k/react-use-servertime";

function MyClock() {
	const { now } = useServerTime({url: "https://karakara.uk/time.json"});

	return <div>The time is {now}</div>;
}

The given URL should return the current time in floating-point seconds

This hook will update the now value once per second, on the second

If you have multiple places which want to use the time, you can use a context provider so that multiple components share a single clock:

import { ServerTimeContext, ServerTimeProvider } from "@shish2k/react-use-servertime";

function MyClock() {
	const { now } = useContext(ServerTimeContext);

	return <div>The time is {now}</div>;
}

function App() {
	return <ServerTimeProvider url="https://karakara.uk/time.json">
		<MyClock />
	</ServerTimeProvider>
}

See demo.html for a self-contained, well-commented example.

Readme

Keywords

Package Sidebar

Install

npm i @shish2k/react-use-servertime

Weekly Downloads

0

Version

0.0.3

License

MIT

Unpacked Size

27.9 kB

Total Files

11

Last publish

Collaborators

  • shish2k