From b62b6f4f9260979a80d3d31a10ebb306fba82aa5 Mon Sep 17 00:00:00 2001 From: Kerry Liu Date: Wed, 2 Jun 2021 08:53:24 -0700 Subject: [PATCH] Header toolbar: useCallback to avoid unnecessary rerenders --- .../components/header/header-toolbar/index.js | 33 +++++++++++-------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/packages/edit-post/src/components/header/header-toolbar/index.js b/packages/edit-post/src/components/header/header-toolbar/index.js index 223ca61be67d1a..13a0e158a196a3 100644 --- a/packages/edit-post/src/components/header/header-toolbar/index.js +++ b/packages/edit-post/src/components/header/header-toolbar/index.js @@ -17,7 +17,7 @@ import { } from '@wordpress/editor'; import { Button, ToolbarItem } from '@wordpress/components'; import { listView, plus } from '@wordpress/icons'; -import { useRef } from '@wordpress/element'; +import { useRef, useCallback } from '@wordpress/element'; import { store as keyboardShortcutsStore } from '@wordpress/keyboard-shortcuts'; /** @@ -26,6 +26,9 @@ import { store as keyboardShortcutsStore } from '@wordpress/keyboard-shortcuts'; import TemplateTitle from '../template-title'; import { store as editPostStore } from '../../../store'; +const preventDefault = ( event ) => { + event.preventDefault(); +}; function HeaderToolbar() { const inserterButton = useRef(); const { setIsInserterOpened, setIsListViewOpened } = useDispatch( @@ -73,6 +76,10 @@ function HeaderToolbar() { /* translators: accessibility text for the editor toolbar */ const toolbarAriaLabel = __( 'Document tools' ); + const toggleListView = useCallback( + () => setIsListViewOpened( ! isListViewOpen ), + [ setIsListViewOpened, isListViewOpen ] + ); const overflowItems = ( <> setIsListViewOpened( ! isListViewOpen ) } + onClick={ toggleListView } shortcut={ listViewShortcut } showTooltip={ ! showIconLabels } /> ); - + const openInserter = useCallback( () => { + if ( isInserterOpened ) { + // Focusing the inserter button closes the inserter popover + inserterButton.current.focus(); + } else { + setIsInserterOpened( true ); + } + }, [ isInserterOpened, setIsInserterOpened ] ); return ( { - event.preventDefault(); - } } - onClick={ () => { - if ( isInserterOpened ) { - // Focusing the inserter button closes the inserter popover - inserterButton.current.focus(); - } else { - setIsInserterOpened( true ); - } - } } + onMouseDown={ preventDefault } + onClick={ openInserter } disabled={ ! isInserterEnabled } icon={ plus } /* translators: button label text should, if possible, be under 16