惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cloudbric
Cloudbric
T
Threat Research - Cisco Blogs
Simon Willison's Weblog
Simon Willison's Weblog
AWS News Blog
AWS News Blog
P
Privacy & Cybersecurity Law Blog
H
Help Net Security
云风的 BLOG
云风的 BLOG
G
GRAHAM CLULEY
Spread Privacy
Spread Privacy
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
A
Arctic Wolf
Project Zero
Project Zero
Engineering at Meta
Engineering at Meta
P
Privacy International News Feed
Blog — PlanetScale
Blog — PlanetScale
Stack Overflow Blog
Stack Overflow Blog
M
MIT News - Artificial intelligence
The Register - Security
The Register - Security
Recorded Future
Recorded Future
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
C
Cisco Blogs
PCI Perspectives
PCI Perspectives
Recent Announcements
Recent Announcements
Martin Fowler
Martin Fowler
A
About on SuperTechFans
W
WeLiveSecurity
GbyAI
GbyAI
V
Vulnerabilities – Threatpost
The GitHub Blog
The GitHub Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Check Point Blog
Y
Y Combinator Blog
月光博客
月光博客
Scott Helme
Scott Helme
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google DeepMind News
Google DeepMind News
F
Fortinet All Blogs
U
Unit 42
G
Google Developers Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Threatpost
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Google Online Security Blog
Google Online Security Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Cisco Talos Blog
Cisco Talos Blog
博客园 - 三生石上(FineUI控件)
Hugging Face - Blog
Hugging Face - Blog
MongoDB | Blog
MongoDB | Blog
博客园 - 司徒正美

Kent C. Dodds Blog

Implementing Hybrid Semantic + Lexical Search Simplifying Containers with Cloudflare Sandboxes Migrating to Workspaces and Nx Offloading FFmpeg with Cloudflare Building Semantic Search on my Content Helping YOU ask ME questions with AI How I used Cursor to Migrate Frameworks The Dow's Start on the Covenant Path 2025 in Review The next chapter: EpicAI.pro AI is taking your job How I increased my visibility Launching Epic Web 2023 in Review Stop Being a Junior RSC with Dan Abramov and Joe Savona Live Stream Fixing a Memory Leak in a Production Node.js App 2022 in Review My Car Accident I Migrated from a Postgres Cluster to Distributed SQLite with LiteFS I'm building EpicWeb.dev A review of my time at Remix Remix: The Yang to React's Yin How I help you build better websites Why I Love Remix The State Initializer Pattern How to React ⚛️ Get a catch block error message with TypeScript Building an awesome image loading experience How Remix makes CSS clashes predictable Introducing the new kentcdodds.com How I built a modern website in 2021 How to use React Context effectively Static vs Unit vs Integration vs E2E Testing for Frontend Apps The Testing Trophy and Testing Classifications Array reduce vs chaining vs for loop Don't Solve Problems, Eliminate Them Super Simple Start to Remix Super Simple Start to ESModules in Node.js JavaScript Pass By Value Function Parameters How to write a Constrained Identity Function (CIF) in TypeScript How to optimize your context value How to write a React Component in TypeScript TypeScript Function Syntaxes Listify a JavaScript Array Build vs Buy: Component Libraries edition Using fetch with TypeScript Define function overload types with TypeScript 2020 in Review Business and Engineering alignment Hi, thanks for reaching out to me 👋 useEffect vs useLayoutEffect Super simple start to Firebase functions Super simple start to Netlify functions Super Simple Start to css variables Favor Progress Over Pride in Open Source Testing Implementation Details How getting into Open Source has been awesome for me useState lazy initialization and function updates Use ternaries rather than && in JSX Application State Management with React Use react-error-boundary to handle errors in React JavaScript to Know for React How I structure Express apps What open source project should I contribute to? When I follow TDD AHA Programming 💡 How I Record Educational Videos Should I write a test or fix a bug? Stop mocking fetch Intentional Career Building Improve test error messages of your abstractions Tracing user interactions with React Eliminate an entire category of bugs with a few simple tools Common mistakes with React Testing Library Super Simple Start to React Stop using client-side route redirects The State Reducer Pattern with React Hooks Function forms Replace axios with a simple custom fetch wrapper How to test custom React hooks React Production Performance Monitoring Should I useState or useReducer? Stop using isLoading booleans Make Your Test Fail Make your own DevTools An Argument for Automation Fix the "not wrapped in act(...)" warning Super Simple Start to ESModules in the Browser Implementing a simple state machine library in JavaScript 2010s Decade in Review Why users care about how you write code Why I avoid nesting closures Don't call a React function component Why your team needs TestingJavaScript.com Inversion of Control Understanding React's key prop How to Enable React Concurrent Mode How to add testing to an existing project Profile a React App for Performance
Wrapping React.useState with TypeScript
2021-01-19 · via Kent C. Dodds Blog

I made a useDarkMode hook that looks like this:

type DarkModeState = 'dark' | 'light'
type SetDarkModeState = React.Dispatch<React.SetStateAction<DarkModeState>>

function useDarkMode() {
	const preferDarkQuery = '(prefers-color-scheme: dark)'
	const [mode, setMode] = React.useState<DarkModeState>(() => {
		const lsVal = window.localStorage.getItem('colorMode')
		if (lsVal) {
			return lsVal === 'dark' ? 'dark' : 'light'
		} else {
			return window.matchMedia(preferDarkQuery).matches ? 'dark' : 'light'
		}
	})

	React.useEffect(() => {
		const mediaQuery = window.matchMedia(preferDarkQuery)
		const handleChange = () => {
			setMode(mediaQuery.matches ? 'dark' : 'light')
		}
		mediaQuery.addEventListener('change', handleChange)
		return () => mediaQuery.removeEventListener('change', handleChange)
	}, [])

	React.useEffect(() => {
		window.localStorage.setItem('colorMode', mode)
	}, [mode])

	// we're doing it this way instead of as an effect so we only
	// set the localStorage value if they explicitly change the default
	return [mode, setMode] as const
}

Then it is used like this:

function App() {
  const [mode, setMode] = useDarkMode()
  return (
    <>
      {/* ... */}
      <Home mode={mode} setMode={setMode} />
      {/* ... */}
      <Page mode={mode} setMode={setMode} />
      {/* ... */}
    </>
  )
}

function Home({
  mode,
  setMode,
}: {
  mode: DarkModeState
  setMode: SetDarkModeState
}) {
  return (
    <>
      {/* ... */}
      <Navigation mode={mode} setMode={setMode} />
      {/* ... */}
    </>
  )
}

function Page({
  mode,
  setMode,
}: {
  mode: DarkModeState
  setMode: SetDarkModeState
}) {
  return (
    <>
      {/* ... */}
      <Navigation mode={mode} setMode={setMode} />
      {/* ... */}
    </>
  )
}

function Navigation({
  mode,
  setMode,
}: {
  mode: DarkModeState
  setMode: SetDarkModeState
}) {
  return (
    <>
      {/* ... */}
      <button onClick={() => setMode(mode === 'light' ? 'dark' : 'light')}>
        {mode === 'light' ? <RiMoonClearLine /> : <RiSunLine />}
      </button>
      {/* ... */}
    </>
  )
}

This works great, and powers the "dark mode" support for all the Epic React workshop apps (for example React Fundamentals).

A closer look

I want to call out a few things about the hook itself that made things work well from a TypeScript perspective. First, let's clear out all the extra stuff and just look at the important bits. We'll even clear out the TypeScript and add it iteratively:

function useDarkMode() {
  const [mode, setMode] = React.useState(() => {
    // ...
    return 'light'
  })

  // ...

  return [mode, setMode]
}

function App() {
  const [mode, setMode] = useDarkMode()
  return (
    <button onClick={() => setMode(mode === 'light' ? 'dark' : 'light')}>
      Toggle from {mode}
    </button>
  )
}

From the get-go, we've got an error when calling setMode:

This expression is not callable.
  Not all constituents of type 'string | React.Dispatch<SetStateAction<string>>' are callable.
    Type 'string' has no call signatures.(2349)

You can read each addition of indentation as "because", so let's read that again:

This expression is not callable. Because not all constituents of type 'string | React.Dispatch<SetStateAction<string>>' are callable. Because type 'string' has no call signatures.(2349)

The "expression" it's referring to is the call to setMode, so it's saying that setMode isn't callable because it can be either React.Dispatch<SetStateAction<string>> (which is a callable function) or string (which is not callable).

For us reading the code we know that setMode is a callable function, so the question is: why is the setMode type both a function and a string?

Let me rewrite something and we'll see if the reason jumps out at you:

const array = useDarkMode()
const mode = array[0]
const setMode = array[1]

The array in this case has the following type:

Array<string | React.Dispatch<React.SetStateAction<string>>>

So the array that's being returned from useDarkMode is an Array with elements that are either a string or a React.Dispatch type. As far as TypeScript is concerned, it has no idea that the first element of the array is the string and the second element is the function. All it knows for sure is that the array has elements of those two types. So when we pull any values out of this array, those values have to be one of the two types.

But React's useState hook manages to ensure when we extract values out of it. Let's take a quick look at their type definition for useState:

function useState<S>(
	initialState: S | (() => S),
): [S, Dispatch<SetStateAction<S>>]

Ah, so they have a return type that is an array with explicit types. So rather than an array of elements that can be one of two types, it's explicitly an array with two elements where the first is the type of state and the second is a Dispatch SetStateAction for that type of state.

So we need to tell TypeScript that we intend to ensure our array values don't ever change. There are a few ways to do this, we could set the return type for our function:

function useDarkMode(): [string, React.Dispatch<React.SetStateAction<string>>] {
	// ...
	return [mode, setMode]
}

Or we could make a specific type for a variable:

function useDarkMode() {
	// ...
	const returnValue: [string, React.Dispatch<React.SetStateAction<string>>] = [
		mode,
		setMode,
	]
	return returnValue
}

Or, even better, TypeScript has this capability built-in. Because TypeScript already knows the types in our array, so we can just tell TypeScript: "the type for this value is constant" so we can cast our value as a const:

function useDarkMode() {
	// ...
	return [mode, setMode] as const
}

And that makes everything happy without having to spend a ton of time typing out our types 😉

And we can take it a step further because with our Dark Mode functionality, the string can be either dark or light so we can do better than TypeScript's inference and pass the possible values explicitly:

function useDarkMode() {
	const [mode, setMode] = React.useState<'dark' | 'light'>(() => {
		// ...
		return 'light'
	})

	// ...

	return [mode, setMode] as const
}

This will help us when we call setMode to ensure we not only call it with a string, but the right type of string. I also created type aliases for this and the dispatch function to make the prop types easier as I pass these values around my app.

Hope that was interesting and helpful to you! Enjoy 🎉