Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type for the setState function of the useState hook?

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

like image 340
cbdeveloper Avatar asked Dec 07 '25 08:12

cbdeveloper


1 Answers

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.

like image 89
Patrick Roberts Avatar answered Dec 09 '25 00:12

Patrick Roberts