[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

posted @ 2021-01-26 03:58  Zhentiw  阅读(131)  评论(0编辑  收藏  举报