The useDebugValue Hook

The useDebugValue Hook is useful for developing custom Hooks that are part of shared libraries. It can be used to show certain values for debugging in React DevTools.

For example, in our useDebouncedUndo custom Hook, we could do the following:

export default function useDebouncedUndo (timeout = 200) {
const [ content, setInput ] = useState('')
const [ undoContent, { set: setContent, ...undoRest } ] = useUndo('')

useDebugValue('init')

const [ setDebounce, cancelDebounce ] = useDebouncedCallback(
(value) => {
setContent(value)
useDebugValue('added to history')
},
timeout
)
useEffect(() => {
cancelDebounce()
setInput(undoContent.present)
useDebugValue(`waiting ${timeout}ms`)
}, [cancelDebounce, undoContent])

function setter (value) {
setInput(value)
setDebounce(value)
}

return [ content, setter, undoRest ]
}

Adding these useDebugValue Hooks will show the following in the React DevTools:

  • When the Hook is initialized: DebouncedUndo: init
  • When a value was entered: DebouncedUndo: waiting 200 ms
  • After debouncing (after 200 ms): DebouncedUndo: added to history
..................Content has been hidden....................

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