'Passing setState as argument to custom hook in react/next.js with typescript
Here is the code that gives me an error:
import { useState, useEffect } from "react";
type Props = {
setState: (value: string) => void;
};
const useSomeCustomHook = ({ setState }: Props) => {
useEffect(() => {
setState("updated value");
}, []);
};
const SomePage = () => {
const [state, setState] = useState("initial value");
useSomeCustomHook(setState);
};
export default SomePage;
I am trying to pass a setState function as an argument to a custom hook, but I get this error:
Argument of type 'Dispatch<SetStateAction<string>>' is not assignable to parameter of
type 'Props'.
Property 'setState' is missing in type 'Dispatch<SetStateAction<string>>' but required
in type 'Props'.
I tried to switch the custom hook with a regular function, and that worked. Does that mean there is something about custom hooks that I don't understand? According to the error, it looks like there is a problem with the props type?
Solution 1:[1]
You expect an object to be passed to useCustomHook but you call it with a function.
Use it like this if you not want to change Props or expect more props later:
const SomePage = () => {
const [state, setState] = useState("initial value");
useSomeCustomHook({setState});
};
Solution 2:[2]
There is a definition for setState in React.
So you need to define the type of your setState function like the following.
type Props = {
setState: Dispatch<SetStateAction<string>>;
};
const useSomeCustomHook = ({ setState }: Props) => {
useEffect(() => {
setState("updated value");
}, []);
};
const SomePage = () => {
const [state, setState] = useState("initial value");
useSomeCustomHook({setState});
};
export default SomePage;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Istvan Tabanyi |
| Solution 2 | Liki Crus |
