DEV Community

Ankit Sahu
Ankit Sahu

Posted on

2

Switching Between Dark and Light in Nextjs13.4 App

Create nextjs app

Create nextjs app

Add darkMode: "class" to tailwind.config.css

Image description

Install next-themes

pnpm install next-themes
Enter fullscreen mode Exit fullscreen mode

Create Provider.tsx file inside app directory

"use client"

import React from 'react'
import {ThemeProvider} from 'next-themes'

function Provider({
    children,
    }: {
        children: React.ReactNode
    }) {
    return (
        <ThemeProvider>
            {children}
        </ThemeProvider>
    )
}

export default Provider
Enter fullscreen mode Exit fullscreen mode

Add following to layout.tsx in app directory

import Provider from './Provider'
import './globals.css'
import { Inter } from 'next/font/google'

const inter = Inter({ subsets: ['latin'] })

export const metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
}

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body className={inter.className}>
        <Provider>
          {children}
        </Provider>
      </body>
    </html>
  )
}

Enter fullscreen mode Exit fullscreen mode

That's it now you just have use useTheme hook to switch between light and dark mode

Create ThemeToggle.tsx file

"use client"
import { useTheme } from 'next-themes'
import React, { useEffect, useState } from 'react'


function ToggleTheme() {
    const [mounted, setMounted] = useState(false)
    const { theme, setTheme } = useTheme()

    useEffect(() => {
        setMounted(true)
    }, [])

    if (!mounted) {
        return null
    }

    return (
        <select value={theme} onChange={e => setTheme(e.target.value)}>
            <option value="system">System</option>
            <option value="dark">Dark</option>
            <option value="light">Light</option>
        </select>
    )
}

export default ToggleTheme
Enter fullscreen mode Exit fullscreen mode

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay