Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React useContext & Typescript: Not an Array Type

I have created the following context using React createContext:

import { useBoolean } from "@chakra-ui/react"
import { createContext, FC } from "react"

type useBooleanReturn = ReturnType<typeof useBoolean>

export const MobileContext = createContext<
  [show: useBooleanReturn[0], setShow: useBooleanReturn[1]] | undefined
>(undefined)

// --- PROVIDER
const MobileProvider: FC = ({ children }) => {
  const [show, setShow] = useBoolean(false)

  return (
    <MobileContext.Provider value={[show, setShow]}>
      {children}
    </MobileContext.Provider>
  )
}

export default MobileProvider

As far as I can tell, this works as it should (at least I am not getting any typescript errors).

I now want to "consume" that context as follows:

import * as React from "react"

import MobileProvider, { MobileContext } from "./context.mobile"

const Mobile = () => {
  const [show, setShow] = React.useContext(MobileContext)
  ...
}

export default Mobile

It is here that I get some typescript errors -- in particular, [show, setShow] is underlined with the red squiggly line and the following message:

Type '[
  show: boolean, 
  setShow: { 
    readonly on: () => void; 
    readonly off: () => void; 
    readonly toggle: () => void; 
    }
  ] | undefined' is not an array type.ts(2461)

I don't understand why this is not an array type or how to fix this.

Any ideas?

Thanks.

like image 336
Moshe Avatar asked Sep 21 '26 21:09

Moshe


1 Answers

I'd do it like this

const [show, setShow] = React.useContext(MobileContext) ?? []

Only thing here is that show and setShow may be undefined. You can actually set default values for these if you want:

const [
  show = false,
  setShow = () => {},
] = React.useContext(MobileContext) ?? []

Though, setting the default value could mess up the type of show and setShow, for example you could set show = 1. So, you know...use responsibly.

like image 104
Paul Huynh Avatar answered Sep 24 '26 13:09

Paul Huynh