'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?
Solution 1:[1]
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())
Solution 2:[2]
Use useCallback() in this situation.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Asaf Aviv |
| Solution 2 | coder9833idls |
