Type for the setState function of the useState hook?

0

Issue

I’m converting my React project to Typescript.

I have this piece of state:

AdminBlogPostContainer.tsx

const [blogPost,setBlogPost] = useState<null | BLOGPOST>(null);

return(
  <AdminBlogPostPage
    blogPost={blogPost as BLOGPOST}
    setBlogPost={setBlogPost}
  />
);

AdminBlogPostPage.tsx

interface AdminBlogPostPage {
  blogPost: BLOGPOST,
  setBlogPost:            // <---- WHAT SHOULD I USE AS TYPE HERE ?
}

const AdminBlogPostPage: React.FC<AdminBlogPostPage> = (props) => {
  console.log("Rendering AdminBlogPostPage...");

  return(
    // ...
  );
};

export default AdminBlogPostPage;

This is the error message:

enter image description here

Solution

Let’s start with some relevant type definitions from @types/react.

declare namespace React {
    // ...
    type SetStateAction<S> = S | ((prevState: S) => S);
    // ...
    type Dispatch<A> = (value: A) => void;
    // ...
    function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];
    // ...
}

From this we can already deduce the type of setBlogPost in the statement

const [blogPost, setBlogPost] = useState<null | BLOGPOST>(null);

which is Dispatch<SetStateAction<null | BLOGPOST>>, but let’s break that down to see what each part means.

setBlogPost: (value: null | BLOGPOST | ((prevState: null | BLOGPOST) => null | BLOGPOST)) => void;

Digesting that one piece at a time working from the outside in, we get the following explanation:

  • setBlogPost: (value: ...) => void

    setBlogPost is a function that accepts a parameter value and returns void.

    • value: null | BLOGPOST | ((prevState: ...) => null | BLOGPOST)

      value is either null, a BLOGPOST, or a function that accepts a parameter prevState and returns null or a BLOGPOST.

      • prevState: null | BLOGPOST

        prevState is either null or a BLOGPOST.

Answered By – Patrick Roberts

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More