type useState setter in child component
Asked Answered
M

3

10

I am trying to pass a useState setter to a child component, but unsure how to type this.

const Parent = () => {
   const [count, setCount] = useState(0);
   return(
     Child count={count} setCount={setCount} />
   );
}

Then in the Child component I am trying to type the setter but I am seeing the following error.

Type 'Dispatch< SetStateAction< string[] > >'is not assignable to type '() => void'.

My code looks like this

type Props = {
  count: number;
  // the issue is the line below
  setCount: () => void;
}

const Child = ({ count, setCount }: Props) => {
    .... code here
}
Melee answered 20/2, 2019 at 10:12 Comment(0)
P
14

You can specify that the setCount prop function expects a number as first argument and the error will go away.

type Props = {
  count: number;
  setCount: (num: number) => void;
}
Postremogeniture answered 20/2, 2019 at 10:27 Comment(1)
I would love to know how to type it the way react does. Because you cant just pass a number to the original setter, you can also pass a function to modify the state using the previous stateBunchy
D
13
const Parent = () => {
   const [myState, setMyState] = useState<YourType>({});
   return(
     <Child count={myState} setCount={setMyState} />
   );
}
import { Dispatch, SetStateAction } from 'react'

type Props = {
  count: YourType;
  setCount: Dispatch<SetStateAction<YourType>>;
}

const Child = ({ count, setCount }: Props) => {
  // works with
  setCount(newState)

  // also with
  setCount(oldState => {
    // ...
    return newState
  })
}
Doersten answered 19/8, 2022 at 19:59 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Assize
C
1

The type of your react useState setter is Dispatch<SetStateAction<T>> where T is the type of your property. You could translate this as dispatching a 'set-state' action. So taking the Props type from your example, it would look like this:

type Props = {
  count: number;
  setCount: Dispatch<SetStateAction<T>>
}

Type definitions: source

Cleodell answered 8/2 at 12:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.