{"id":351371,"date":"2024-05-20T12:38:37","date_gmt":"2024-05-20T12:38:37","guid":{"rendered":"http:\/\/savepearlharbor.com\/?p=351371"},"modified":"-0001-11-30T00:00:00","modified_gmt":"-0001-11-29T21:00:00","slug":"","status":"publish","type":"post","link":"https:\/\/savepearlharbor.com\/?p=351371","title":{"rendered":"<span>React Custom Hook: useDarkMode<\/span>"},"content":{"rendered":"<div><!--[--><!--]--><\/div>\n<div id=\"post-content-body\">\n<div>\n<div class=\"article-formatted-body article-formatted-body article-formatted-body_version-2\">\n<div xmlns=\"http:\/\/www.w3.org\/1999\/xhtml\">\n<p>In this article series, we embark on a journey through the realm of custom React hooks, discovering their immense potential for elevating your development projects. Our focus today is on the &#171;useDarkMode&#187; hook, one of the many carefully crafted hooks available in the collection of React custom hooks.<\/p>\n<p>Github:\u00a0<a href=\"https:\/\/github.com\/sergeyleschev\/react-custom-hooks\" rel=\"noopener noreferrer nofollow\"><u>https:\/\/github.com\/sergeyleschev\/react-custom-hooks<\/u><\/a><\/p>\n<pre><code class=\"javascript\">import { useEffect } from \"react\" import useMediaQuery from \"..\/useMediaQuery\/useMediaQuery\" import { useLocalStorage } from \"..\/useStorage\/useStorage\"  export default function useDarkMode() {     const [darkMode, setDarkMode] = useLocalStorage(\"useDarkMode\")     const prefersDarkMode = useMediaQuery(\"(prefers-color-scheme: dark)\")     const enabled = darkMode ?? prefersDarkMode      useEffect(() => {         document.body.classList.toggle(\"dark-mode\", enabled)     }, [enabled])      return [enabled, setDarkMode] }<\/code><\/pre>\n<p>This custom hook combines two other handy hooks\u00a0<code>useMediaQuery<\/code>\u00a0and\u00a0<code>useStorage<\/code>, to provide a seamless dark mode experience. It automatically detects the user&#8217;s preferred color scheme and persists the dark mode state in the browser&#8217;s local storage.<\/p>\n<p>One of the main advantages of &#171;<strong>useDarkMode<\/strong>&#187; is its simplicity. With just a few lines of code, you can enable dark mode in your React application. By invoking this hook, you&#8217;ll receive the current dark mode state and a function to toggle it.<\/p>\n<p>The &#171;useDarkMode&#187; hook dynamically updates the HTML body class to apply the &#171;dark-mode&#187; styling whenever dark mode is enabled. This approach ensures consistency across all components without the need for manual class manipulation.<\/p>\n<pre><code class=\"css\">body.dark-mode {     background-color: #333; }<\/code><\/pre>\n<p>You can use the &#171;useDarkMode&#187; hook in various scenarios. Whether you&#8217;re building a blog, e-commerce platform, or a content-heavy application, dark mode can enhance the user experience, reduce eye strain, and conserve device battery life. The possibilities are endless, and this custom hook makes it a breeze to implement.<\/p>\n<p>To make it even easier, I&#8217;ve included a simple example component, &#171;DarkModeComponent,&#187; that showcases how to use the &#171;useDarkMode&#187; hook. By clicking the &#171;Toggle Dark Mode&#187; button, you can instantly switch between light and dark themes. The button&#8217;s appearance changes dynamically, reflecting the current mode.<\/p>\n<pre><code class=\"javascript\">import useDarkMode from \".\/useDarkMode\" import \".\/body.css\"  export default function DarkModeComponent() {     const [darkMode, setDarkMode] = useDarkMode()     return (         &lt;button             onClick={() => setDarkMode(prevDarkMode => !prevDarkMode)}             style={{                 border: `1px solid ${darkMode ? \"white\" : \"black\"}`,                 background: \"none\",                 color: darkMode ? \"white\" : \"black\",             }}         >             Toggle Dark Mode         &lt;\/button>     ) }<\/code><\/pre>\n<p>Note that browsers have native support for dark mode. To opt in:<\/p>\n<pre><code class=\"xml\">&lt;meta name=\"color-scheme\" content=\"light dark\"><\/code><\/pre>\n<p>Most browsers will trigger a light-on-dark color scheme just by doing this. In CSS you can use media queries:<\/p>\n<pre><code class=\"css\">@media (prefers-color-scheme: dark) {     .some-component {         color: white;         background-color: #1c1c1c;     } } <\/code><\/pre>\n<p>This way your site will automatically adapt to the dark mode setting of the browser or OS.<\/p>\n<p>This approach leverages the browser&#8217;s built-in functionality, and your suggestion provides an excellent alternative for implementing dark mode without relying solely on custom React hooks. But..<\/p>\n<p><strong>Benefits of &#171;useDarkMode&#187; Custom Hook:<\/strong><\/p>\n<ol>\n<li>\n<p><strong>Full Control and Customization<\/strong>: With the &#171;useDarkMode&#187; custom hook, you have complete control over the design, color palette, and styling of your dark mode. You can tailor the appearance to match your brand and design intent.<\/p>\n<\/li>\n<li>\n<p><strong>Simplified CSS<\/strong>: The custom hook abstracts the complexity of toggling between light and dark mode styles, reducing the complexity of your CSS codebase.<\/p>\n<\/li>\n<li>\n<p><strong>User-Initiated Toggle<\/strong>: The hook allows users to switch between light and dark modes within your website, independent of their system-wide settings. This can improve user engagement and experience.<\/p>\n<\/li>\n<li>\n<p><strong>Integration with UI Components<\/strong>: You can easily integrate the &#171;useDarkMode&#187; hook into your UI components, allowing for a seamless and unified dark mode experience throughout your application.<\/p>\n<\/li>\n<\/ol>\n<p><strong>Drawbacks of Browser&#8217;s Built-in Dark Mode:<\/strong><\/p>\n<ol>\n<li>\n<p><em>Limited Customization<\/em>: Relying solely on browser dark mode settings limits your ability to customize the design and appearance of your dark mode to align with your branding and user experience goals.<\/p>\n<\/li>\n<li>\n<p><em>Dependency on User Settings<\/em>: Your website&#8217;s appearance depends on the user&#8217;s system-wide dark mode setting. This might not align with your design intent and could lead to a disconnect between your brand and the user experience.<\/p>\n<\/li>\n<li>\n<p><em>Compatibility Issues<\/em>: Not all browsers or platforms support the prefers-color-scheme media query, leading to potential compatibility issues and inconsistent behavior.<\/p>\n<\/li>\n<li>\n<p><em>Limited Accessibility Control<\/em>: Browser-based dark mode might not provide the accessibility features needed for all users, potentially excluding those with specific visual needs.<\/p>\n<\/li>\n<\/ol>\n<p>&#171;<em>useDarkMode<\/em>&#187; custom hook offers greater control, customization, consistency, and accessibility over relying solely on the browser&#8217;s built-in dark mode variant. It empowers you to create a tailored dark mode experience that aligns with your design goals while overcoming the limitations and potential drawbacks associated with browser-native dark mode.<\/p>\n<p>Full Version | React Custom Hooks: <a href=\"https:\/\/habr.com\/en\/articles\/746760\/\" rel=\"noopener noreferrer nofollow\">https:\/\/habr.com\/en\/articles\/746760\/<\/a><\/p>\n<\/p>\n<\/div>\n<\/div>\n<\/div>\n<p><!----><!----><\/div>\n<p><!----><!----><br \/> \u0441\u0441\u044b\u043b\u043a\u0430 \u043d\u0430 \u043e\u0440\u0438\u0433\u0438\u043d\u0430\u043b \u0441\u0442\u0430\u0442\u044c\u0438 <a href=\"https:\/\/habr.com\/ru\/articles\/752774\/\"> https:\/\/habr.com\/ru\/articles\/752774\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<div><!--[--><!--]--><\/div>\n<div id=\"post-content-body\">\n<div>\n<div class=\"article-formatted-body article-formatted-body article-formatted-body_version-2\">\n<div xmlns=\"http:\/\/www.w3.org\/1999\/xhtml\">\n<p>In this article series, we embark on a journey through the realm of custom React hooks, discovering their immense potential for elevating your development projects. Our focus today is on the &#171;useDarkMode&#187; hook, one of the many carefully crafted hooks available in the collection of React custom hooks.<\/p>\n<p>Github:\u00a0<a href=\"https:\/\/github.com\/sergeyleschev\/react-custom-hooks\" rel=\"noopener noreferrer nofollow\"><u>https:\/\/github.com\/sergeyleschev\/react-custom-hooks<\/u><\/a><\/p>\n<pre><code class=\"javascript\">import { useEffect } from \"react\" import useMediaQuery from \"..\/useMediaQuery\/useMediaQuery\" import { useLocalStorage } from \"..\/useStorage\/useStorage\"  export default function useDarkMode() {     const [darkMode, setDarkMode] = useLocalStorage(\"useDarkMode\")     const prefersDarkMode = useMediaQuery(\"(prefers-color-scheme: dark)\")     const enabled = darkMode ?? prefersDarkMode      useEffect(() => {         document.body.classList.toggle(\"dark-mode\", enabled)     }, [enabled])      return [enabled, setDarkMode] }<\/code><\/pre>\n<p>This custom hook combines two other handy hooks\u00a0<code>useMediaQuery<\/code>\u00a0and\u00a0<code>useStorage<\/code>, to provide a seamless dark mode experience. It automatically detects the user&#8217;s preferred color scheme and persists the dark mode state in the browser&#8217;s local storage.<\/p>\n<p>One of the main advantages of &#171;<strong>useDarkMode<\/strong>&#187; is its simplicity. With just a few lines of code, you can enable dark mode in your React application. By invoking this hook, you&#8217;ll receive the current dark mode state and a function to toggle it.<\/p>\n<p>The &#171;useDarkMode&#187; hook dynamically updates the HTML body class to apply the &#171;dark-mode&#187; styling whenever dark mode is enabled. This approach ensures consistency across all components without the need for manual class manipulation.<\/p>\n<pre><code class=\"css\">body.dark-mode {     background-color: #333; }<\/code><\/pre>\n<p>You can use the &#171;useDarkMode&#187; hook in various scenarios. Whether you&#8217;re building a blog, e-commerce platform, or a content-heavy application, dark mode can enhance the user experience, reduce eye strain, and conserve device battery life. The possibilities are endless, and this custom hook makes it a breeze to implement.<\/p>\n<p>To make it even easier, I&#8217;ve included a simple example component, &#171;DarkModeComponent,&#187; that showcases how to use the &#171;useDarkMode&#187; hook. By clicking the &#171;Toggle Dark Mode&#187; button, you can instantly switch between light and dark themes. The button&#8217;s appearance changes dynamically, reflecting the current mode.<\/p>\n<pre><code class=\"javascript\">import useDarkMode from \".\/useDarkMode\" import \".\/body.css\"  export default function DarkModeComponent() {     const [darkMode, setDarkMode] = useDarkMode()     return (         &lt;button             onClick={() => setDarkMode(prevDarkMode => !prevDarkMode)}             style={{                 border: `1px solid ${darkMode ? \"white\" : \"black\"}`,                 background: \"none\",                 color: darkMode ? \"white\" : \"black\",             }}         >             Toggle Dark Mode         &lt;\/button>     ) }<\/code><\/pre>\n<p>Note that browsers have native support for dark mode. To opt in:<\/p>\n<pre><code class=\"xml\">&lt;meta name=\"color-scheme\" content=\"light dark\"><\/code><\/pre>\n<p>Most browsers will trigger a light-on-dark color scheme just by doing this. In CSS you can use media queries:<\/p>\n<pre><code class=\"css\">@media (prefers-color-scheme: dark) {     .some-component {         color: white;         background-color: #1c1c1c;     } } <\/code><\/pre>\n<p>This way your site will automatically adapt to the dark mode setting of the browser or OS.<\/p>\n<p>This approach leverages the browser&#8217;s built-in functionality, and your suggestion provides an excellent alternative for implementing dark mode without relying solely on custom React hooks. But..<\/p>\n<p><strong>Benefits of &#171;useDarkMode&#187; Custom Hook:<\/strong><\/p>\n<ol>\n<li>\n<p><strong>Full Control and Customization<\/strong>: With the &#171;useDarkMode&#187; custom hook, you have complete control over the design, color palette, and styling of your dark mode. You can tailor the appearance to match your brand and design intent.<\/p>\n<\/li>\n<li>\n<p><strong>Simplified CSS<\/strong>: The custom hook abstracts the complexity of toggling between light and dark mode styles, reducing the complexity of your CSS codebase.<\/p>\n<\/li>\n<li>\n<p><strong>User-Initiated Toggle<\/strong>: The hook allows users to switch between light and dark modes within your website, independent of their system-wide settings. This can improve user engagement and experience.<\/p>\n<\/li>\n<li>\n<p><strong>Integration with UI Components<\/strong>: You can easily integrate the &#171;useDarkMode&#187; hook into your UI components, allowing for a seamless and unified dark mode experience throughout your application.<\/p>\n<\/li>\n<\/ol>\n<p><strong>Drawbacks of Browser&#8217;s Built-in Dark Mode:<\/strong><\/p>\n<ol>\n<li>\n<p><em>Limited Customization<\/em>: Relying solely on browser dark mode settings limits your ability to customize the design and appearance of your dark mode to align with your branding and user experience goals.<\/p>\n<\/li>\n<li>\n<p><em>Dependency on User Settings<\/em>: Your website&#8217;s appearance depends on the user&#8217;s system-wide dark mode setting. This might not align with your design intent and could lead to a disconnect between your brand and the user experience.<\/p>\n<\/li>\n<li>\n<p><em>Compatibility Issues<\/em>: Not all browsers or platforms support the prefers-color-scheme media query, leading to potential compatibility issues and inconsistent behavior.<\/p>\n<\/li>\n<li>\n<p><em>Limited Accessibility Control<\/em>: Browser-based dark mode might not provide the accessibility features needed for all users, potentially excluding those with specific visual needs.<\/p>\n<\/li>\n<\/ol>\n<p>&#171;<em>useDarkMode<\/em>&#187; custom hook offers greater control, customization, consistency, and accessibility over relying solely on the browser&#8217;s built-in dark mode variant. It empowers you to create a tailored dark mode experience that aligns with your design goals while overcoming the limitations and potential drawbacks associated with browser-native dark mode.<\/p>\n<p>Full Version | React Custom Hooks: <a href=\"https:\/\/habr.com\/en\/articles\/746760\/\" rel=\"noopener noreferrer nofollow\">https:\/\/habr.com\/en\/articles\/746760\/<\/a><\/p>\n<\/p>\n<\/div>\n<\/div>\n<\/div>\n<p><!----><!----><\/div>\n<p><!----><!----><br \/> \u0441\u0441\u044b\u043b\u043a\u0430 \u043d\u0430 \u043e\u0440\u0438\u0433\u0438\u043d\u0430\u043b \u0441\u0442\u0430\u0442\u044c\u0438 <a href=\"https:\/\/habr.com\/ru\/articles\/752774\/\"> https:\/\/habr.com\/ru\/articles\/752774\/<\/a><br \/><\/br><\/br><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[],"tags":[],"class_list":["post-351371","post","type-post","status-publish","format-standard","hentry"],"_links":{"self":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts\/351371","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=351371"}],"version-history":[{"count":0,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts\/351371\/revisions"}],"wp:attachment":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=351371"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=351371"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=351371"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}