From f7c3b5e309b7927e522215ba0847299c8d96fca5 Mon Sep 17 00:00:00 2001 From: MohammadAli Karimi Date: Tue, 23 Apr 2024 16:51:25 +0400 Subject: [PATCH] Update react usage to custom hook --- readme.md | 38 ++++++++++++++++++++++++-------------- 1 file changed, 24 insertions(+), 14 deletions(-) diff --git a/readme.md b/readme.md index a9f370d..860c8ba 100644 --- a/readme.md +++ b/readme.md @@ -36,23 +36,33 @@ npm install devtools-detect ## React Usage ```jsx -import { useState } from 'react'; +import {useState, useEffect} from 'react'; import devtoolsDetect from 'devtools-detect'; +export function useDevToolsStatus() { + const [isDevToolsOpen, setIsDevToolsOpen] = useState(devtoolsDetect.isOpen); + + useEffect(() => { + const handleChange = event => { + setIsDevToolsOpen(event.detail.isOpen); + }; + + window.addEventListener('devtoolschange', handleChange); + + return () => { + window.removeEventListener('devtoolschange', handleChange); + }; + }, []); + + return isDevToolsOpen; +} +``` +```jsx +import {useDevToolsStatus} from './useDevToolsStatus.js'; + export default function App() { - const [isDevToolsOpen, setIsDevToolsOpen] = useState(devtoolsDetect.isOpen); - - if (window) { - window.addEventListener('devtoolschange', function (e) { - if (e.detail.isOpen) { - setIsDevToolsOpen(true); - } else { - setIsDevToolsOpen(false); - } - }); - } - - return isDevToolsOpen ? 'OPEN' : 'CLOSE'; + const isDevToolsOpen = useDevToolsStatus(); + return isDevToolsOpen ? 'OPEN' : 'CLOSED'; } ```