[React] useState with Typescript

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

Example:

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

Using:

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

Ref post

原文地址:https://www.cnblogs.com/Answer1215/p/14328421.html