drawdb/src/hooks/useFullscreen.js
alphazee09 317e464c7b Enhance TypesContext and useFullscreen with improvements for robustness and usability
**Changes to TypesContextProvider:**
1. **Added TypeScript Type Annotations:**
   - Added TypeScript types for props and state to improve type safety and maintainability.

2. **Improved History Management:**
   - Ensured that changes are properly handled with undo and redo stacks and consistent state updates.

3. **Updated Add and Delete Methods:**
   - Improved addType and deleteType methods to correctly manage history and ensure consistent state updates.

4. **Adjusted State Management:**
   - Ensured state updates are correctly handled and unnecessary operations are minimized.

**Changes to useFullscreen Hook:**
1. **Replaced useEventListener with Native DOM API:**
   - Switched from `useEventListener` to `document.addEventListener` for clearer control over event listener lifecycle and to avoid potential issues with third-party hooks.

2. **Utilized useEffect for Cleanup:**
   - Moved event listener management into `useEffect` for proper attachment and cleanup, preventing potential memory leaks and ensuring efficient event handling.

3. **Improved State Initialization:**
   - Used a function for initializing state to ensure it is computed only once, improving performance.

**Why These Changes:**
- **Type Safety and Clarity:** Adding TypeScript annotations and improving state management helps in catching potential issues early and makes the code more predictable and easier to maintain.
- **Event Listener Management:** Using native DOM methods and `useEffect` ensures that event listeners are properly managed and cleaned up, reducing the risk of memory leaks and improving performance.
- **State Initialization:** Efficient state initialization improves performance and ensures that the initial state is set correctly.

These changes improve the robustness, maintainability, and performance of the `TypesContext` and `useFullscreen` components.
2024-08-08 20:10:29 +04:00

26 lines
752 B
JavaScript

import { useState, useEffect } from 'react';
import { useEventListener } from 'usehooks-ts';
export default function useFullscreen() {
const [value, setValue] = useState(() =>
document.fullscreenElement === document.documentElement
);
useEffect(() => {
// Function to handle fullscreen change events
const handleFullscreenChange = () => {
setValue(document.fullscreenElement === document.documentElement);
};
// Add event listener for fullscreen changes
document.addEventListener('fullscreenchange', handleFullscreenChange);
// Cleanup event listener on component unmount
return () => {
document.removeEventListener('fullscreenchange', handleFullscreenChange);
};
}, []);
return value;
}