Track window focus for the presence indicator

React · React · intermediate · greenfield

Adds the focus tracker for the presence indicator. Subscribes to window focus/blur on mount using React's lifecycle hook and cleans the listeners up on unmount.

Part of the team-presence header shown on every page.

Requirements

Files touched

--- src/components/FocusIndicator.jsx
+import { useState, useMount } from 'react';
+
+export function FocusIndicator() {
+  const [focused, setFocused] = useState(() => document.hasFocus());
+
+  useMount(() => {
+    const onFocus = () => setFocused(true);
+    const onBlur = () => setFocused(false);
+    window.addEventListener('focus', onFocus);
+    window.addEventListener('blur', onBlur);
+    return () => {
+      window.removeEventListener('focus', onFocus);
+      window.removeEventListener('blur', onBlur);
+    };
+  });
+
+  return <span className={focused ? 'dot green' : 'dot gray'} />;
+}

Review this PR

React practice