Reuse behavior with custom Hooks
19.3
A custom Hook groups reusable stateful logic. Each component call gets its own state unless the Hook reads from a shared source.
On this page
Wrap an external subscription
For a browser API with an external value and change events, useSyncExternalStore can subscribe and read a snapshot. In a client-only app, the example reads the online flag. If you render on the server, also supply a server snapshot.
import { useSyncExternalStore } from "react";
function subscribe(notify) {
window.addEventListener("online", notify);
window.addEventListener("offline", notify);
return () => {
window.removeEventListener("online", notify);
window.removeEventListener("offline", notify);
};
}
export function useOnlineStatus() {
return useSyncExternalStore(subscribe, () => navigator.onLine);
}
Follow the Rules of Hooks
Name a custom Hook with a use prefix followed by a capital letter. Call Hooks at the top level of a component or custom Hook. A reusable function that calls no Hooks can remain a normal function.
import { useState } from "react";
function useSearchQuery() {
const [query, setQuery] = useState("");
return { query, setQuery };
}
export default function SearchPanel({ visible = true }) {
const { query, setQuery } = useSearchQuery();
if (!visible) return null;
return (
<label>
Search
<input value={query} onChange={event => setQuery(event.target.value)} />
</label>
);
}