feat: add useBattery hook - #1667
Conversation
There was a problem hiding this comment.
Pull request overview
This PR adds a new useBattery hook that tracks device battery state using the Battery Status API. The hook provides battery charge level, charging status, and time estimates, with proper SSR safety and event subscription handling.
Changes:
- Adds
useBatteryhook with support for tracking battery charging state, level, and time estimates - Includes comprehensive test coverage with 8 DOM tests and 5 SSR tests
- Adds Battery API mock setup for testing environment
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| src/useBattery/index.ts | Core hook implementation that subscribes to Battery Status API events and returns battery state |
| src/useBattery/index.dom.test.ts | DOM environment tests covering hook behavior, event subscriptions, and state updates |
| src/useBattery/index.ssr.test.ts | SSR tests verifying safe fallback behavior when Battery API is unavailable |
| src/util/testing/setup/battery.test.ts | Test setup file that mocks the Battery Status API for vitest |
| vitest.config.ts | Configuration update to include battery test setup |
| src/index.ts | Exports the new useBattery hook under the Navigator section |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
d2afe76 to
11be20c
Compare
Port `useBattery` from react-use, exposing charging state, charge level and the charging/discharging time estimates from the Battery Status API. The hook is SSR-safe: access to `navigator.getBattery` is guarded by `isBrowser`, so a server render reports `isSupported: false` with undefined readings rather than throwing. Listeners are not attached when the effect is cleaned up while `getBattery()` is still pending, and a rejected `getBattery()` falls back to the unfetched state instead of leaving an unhandled rejection. Refs react-hookz#33
11be20c to
90d7c5f
Compare
|
I have rebased this onto the latest What I changed:
Checks on my machine: CI has not run here yet. Fork PRs need a maintainer to approve the run. Two things I would like your opinion on:
|
Summary
useBatteryhook that tracks device battery state using the Battery Status API{ isSupported, fetched, charging, chargingTime, dischargingTime, level }Test plan
Partial implementation of #33 (sensor hooks from react-use)