Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

not assignable to type '() => void' error when using React useMemo() with TypeScript?

I have a very simple react app with typescript.

import React, { useState, useMemo } from "react";
import { Editor as Draft, EditorState } from "draft-js";

const Editor: React.FC = () => {
  const [editorState, setEditorState] = useState<() => EditorState>(() =>
    EditorState.createEmpty()
  );

  const handleEditorChange = useMemo(
    (nextEditorState: EditorState) => setEditorState(nextEditorState),
    [editorState]
  );

  return (
    <div>
      <Draft editorState={editorState} onChange={handleEditorChange} />
    </div>
  );
};

export default Editor;

I'm trying to get it to work using useMemo() but when I wrap handleEditorChange in useMemo I get the following error:

argument of type '(nextEditorState: EditorState) => void' is not assignable to parameter of type '() => void'  

How to correctly use TypeScript here and get rid of the error?

like image 923
zakaria Avatar asked Sep 19 '25 02:09

zakaria


2 Answers

Typescript requires that useMemo has an explicit return.

export function useHello(): string {
    return useMemo<string>(() => {
        return 'hello';
    }, []);
}
like image 191
Hummel Avatar answered Sep 20 '25 18:09

Hummel


useMemo is used to memoize the return value of the function provided to it but you are using it as an onChange handler.

So remove it and just use the function as the handler

const handleEditorChange = (nextEditorState: EditorState) => 
  setEditorState(nextEditorState)

Second, you type your state as a function that returns the EditorState which is not correct, you want the type to be EditorState.

TypeScript can also infer the type so you don't even need to type it

const [editorState, setEditorState] = useState(EditorState.createEmpty())
like image 24
Asaf Aviv Avatar answered Sep 20 '25 18:09

Asaf Aviv