DEV Community

Kozo Oeda
Kozo Oeda

Posted on

Introducing react-hook-quill

I developed react-hook-quill, a lightweight wrapper for Quill, a rich text editor.

import { memo, useRef } from 'react';
import 'quill/dist/quill.snow.css';
import { Delta } from 'quill';
import { useQuill, usePersistentDelta } from 'react-hook-quill';

const Editor = memo(() => {
  const ref = useRef<HTMLDivElement>(null);
  const { persistentDeltaSetting } = usePersistentDelta(
    {
      containerRef: ref,
      options: {
        theme: 'snow'
      }
    },
    new Delta().insert('Hello Quill')
  );

  useQuill({ setting: persistentDeltaSetting });

  return (
    <div ref={ref} />
  );
});
Enter fullscreen mode Exit fullscreen mode

In this post, I will briefly explain the design of this wrapper.

The 1st issue

The first issue is that Quill is not developed specifically for React. It is a vanilla JS(TS) editor. The goal of this wrapper is not to interfere with the design of either React or Quill.
My approach was to use useEffect. In many cases, it is better to avoid using useEffect, but in this case, it was a good fit for the design of this wrapper.

Using useEffect in the custom hook(useQuill) hides the mechanics inside. People may not be aware that Quill is initialized after the DOM has been mounted.
In most cases, this doesn't need to be something people are aware of, but in some cases, it is necessary, such as with SSR.
Currently, the solution is to document it as a note.

The 2nd issue

The second issue is how to best control user edits.
In some cases, it may be better to store user edits in the state of React, but in other cases, it triggers a re-render with every change, which can be an overhead for the application.

To solve this issue, I prepared two custom hooks for setting up useQuill.
One is usePersistentDelta, and the second is useSyncDelta.
This acts like syntactic sugar for general settings. usePersistentDelta does not track user edits on the React side, so user edits don't trigger re-renders.
On the other hand, useSyncDelta syncs user edits on the React side.
Of course, you can also manually use useQuill.

overview

Even a small wrapper has many aspects to consider, but this is also the fun part of development.

Link

Top comments (0)