Skip to content

Commit

Permalink
Block edit: avoid memoized block context in favour of useSelect
Browse files Browse the repository at this point in the history
  • Loading branch information
ellatrix committed Feb 25, 2021
1 parent 4700919 commit e20310d
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 34 deletions.
Original file line number Diff line number Diff line change
@@ -1,15 +1,7 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`BlockControls should render a dynamic toolbar of controls 1`] = `
<ContextProvider
value={
Object {
"clientId": undefined,
"isSelected": true,
"name": undefined,
}
}
>
<ContextProvider>
<WithFilters(Edit)
isSelected={true}
>
Expand Down
31 changes: 23 additions & 8 deletions packages/block-editor/src/components/block-edit/context.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,36 @@
* WordPress dependencies
*/
import { createContext, useContext } from '@wordpress/element';
import { useSelect } from '@wordpress/data';

const Context = createContext( {
name: '',
isSelected: false,
clientId: null,
} );
/**
* Internal dependencies
*/
import { store as blockEditorStore } from '../../store';

const Context = createContext();
const { Provider } = Context;

export { Provider as BlockEditContextProvider };

/**
* A hook that returns the block edit context.
* A hook that returns the block client ID, name and selected status.
*
* @return {Object} Block edit context
* @return {Object} Block client ID, name and selected status.
*/
export function useBlockEditContext() {
return useContext( Context );
const clientId = useContext( Context );
return useSelect(
( select ) => {
const { getBlockName, isBlockSelected } = select(
blockEditorStore
);
return {
clientId,
name: getBlockName( clientId ),
isSelected: isBlockSelected( clientId ),
};
},
[ clientId ]
);
}
18 changes: 1 addition & 17 deletions packages/block-editor/src/components/block-edit/index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
/**
* WordPress dependencies
*/
import { useMemo } from '@wordpress/element';

/**
* Internal dependencies
*/
Expand All @@ -12,19 +7,8 @@ import { BlockEditContextProvider, useBlockEditContext } from './context';
export { useBlockEditContext };

export default function BlockEdit( props ) {
const { name, isSelected, clientId } = props;
const context = {
name,
isSelected,
clientId,
};
return (
<BlockEditContextProvider
// It is important to return the same object if props haven't
// changed to avoid unnecessary rerenders.
// See https://reactjs.org/docs/context.html#caveats.
value={ useMemo( () => context, Object.values( context ) ) }
>
<BlockEditContextProvider value={ props.clientId }>
<Edit { ...props } />
</BlockEditContextProvider>
);
Expand Down

0 comments on commit e20310d

Please sign in to comment.