Skip to content

Commit

Permalink
Header toolbar: useCallback to avoid unnecessary rerenders
Browse files Browse the repository at this point in the history
  • Loading branch information
gwwar committed Jun 2, 2021
1 parent 19017d7 commit b62b6f4
Showing 1 changed file with 19 additions and 14 deletions.
33 changes: 19 additions & 14 deletions packages/edit-post/src/components/header/header-toolbar/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';

/**
Expand All @@ -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(
Expand Down Expand Up @@ -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 = (
<>
<ToolbarItem
Expand All @@ -90,13 +97,20 @@ function HeaderToolbar() {
isPressed={ isListViewOpen }
/* translators: button label text should, if possible, be under 16 characters. */
label={ __( 'List View' ) }
onClick={ () => 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 (
<NavigableToolbar
className="edit-post-header-toolbar"
Expand All @@ -109,17 +123,8 @@ function HeaderToolbar() {
className="edit-post-header-toolbar__inserter-toggle"
variant="primary"
isPressed={ isInserterOpened }
onMouseDown={ ( event ) => {
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
Expand Down

0 comments on commit b62b6f4

Please sign in to comment.