Search code examples
reactjstypescriptnext.jsreact-propsreact-custom-hooks

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

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