javascriptreactjsreact-usememo

Access latest state in useMemo


I am using react-quill, and it's requirement is that modules prop must be cached and shouldn't change. I am using useMemo hook to memoize it. The object is:

const modules = useMemo(() => ({
  key: {
    value: {
      handler: handlerFunc
    }
  }), [])

and it's used like:

<Quill
  modules={modules}
  value={value}
  onChange={onChange}
  // value and onChange are props
/>

handleFunc in modules object, just console logs value prop. The issue is that value is not latest, it's the first value. I tried same thing in class component and I was able to get the value and it works perfectly fine, but unfortunately it doesn't work with useMemo. Please note, I can't just put [value] in second argument of useMemo as modules shouldn't be changed.

Class component implementation:

class MyComponent extends React.Component {
  constructor() {
    super()
    this.handlerFunc = this.handlerFunc.bind(this)
    this.modules = this.initModules(this.handlerFunc)
  }

  initModules(handlerFunc) {
    return {
      key: {
        value: {
          handler: handlerFunc,
        },
      },
    }
  }

  handlerFunc() {
    console.log(this.props.value)
  }
}

But I can't use class-component as it's a requirement to use functional-components only. Is there any way, I can have latest value in useMemo, or yet any other solution?


Solution

  • Why you are not assigning a ref to the editor and getting the value from it, instead of having it from value prop?

    const editor = this.reactQuillRef.getEditor();
    editor.getText(); // getText, getHTML or whatever
    

    Here's the link