Home > database >  Passing setState as argument to custom hook in react/next.js with typescript
Passing setState as argument to custom hook in react/next.js with typescript

Time:04-11

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?

CodePudding user response:

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});
};

CodePudding user response:

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;
  • Related