Using the useDebouncedUndo Hook

Finally, we are going to replace all debounced undo logic in the src/post/CreatePost.js file with our custom useDebouncedUndo Hook. Doing so will make our component code much cleaner and easier to read. Furthermore, we can reuse the same debounced undo functionality in other components later.

Let's get started using the Debounced Undo Hook in the CreatePost component by following these steps:

  1. Edit src/post/CreatePost.js and import the useDebouncedUndo Hook:
import { useUserState, useDispatch, useDebouncedUndo, useAPICreatePost } from '../hooks'
  1. Then, remove the following code related to debounced undo handling:
    const [ content, setInput ] = useState('')
const [ undoContent, {
set: setContent,
undo,
redo,
canUndo,
canRedo
} ] = useUndo('')

const [ setDebounce, cancelDebounce ] = useDebouncedCallback(
(value) => {
setContent(value)
},
200
)
useEffect(() => {
cancelDebounce()
setInput(undoContent.present)
}, [cancelDebounce, undoContent])

Replace it with our custom useDebouncedUndo Hook, as follows:

    const [ content, setContent, { undo, redo, canUndo, canRedo } ] = useDebouncedUndo()
  1. Finally, remove the following setter functions in our handleContent function (marked in bold):
    function handleContent (e) {
const { value } = e.target
setInput(value)
setDebounce(value)
}

We can now use the setContent function provided by our custom Hook instead:

    function handleContent (e) {
const { value } = e.target
setContent(value)
}

As you can see, our code is much cleaner, more concise, and easier to read now. Furthermore, we can reuse the Debounced Undo Hook in other components later on.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.120.109