Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix newlines in block editor after a user mention #41749

Closed
wants to merge 3 commits into from
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Autocomplete: wrap onChangeOptions in useCallback
  • Loading branch information
chad1008 committed Jun 15, 2022
commit 308bab23bd8f6ea686eb4d2c47a8e79332c0fe66
18 changes: 11 additions & 7 deletions packages/components/src/autocomplete/index.js
Original file line number Diff line number Diff line change
@@ -12,6 +12,7 @@ import {
useState,
useRef,
useMemo,
useCallback,
} from '@wordpress/element';
import {
ENTER,
@@ -210,13 +211,16 @@ function useAutocomplete( {
*
* @param {Array} options
*/
function onChangeOptions( options ) {
setSelectedIndex(
options.length === filteredOptions.length ? selectedIndex : 0
);
setFilteredOptions( options );
announce( options );
}
const onChangeOptions = useCallback(
( options ) => {
setSelectedIndex(
options.length === filteredOptions.length ? selectedIndex : 0
);
setFilteredOptions( options );
announce( options );
},
[ announce, filteredOptions.length, selectedIndex ]
);
Comment on lines +217 to +226
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So... I'm starting to think about when it's better to use a useCallback vs. putting the callback in a ref.

In this case, the ref approach would be to change this

useLayoutEffect( () => {
onChangeOptions( items );
}, [ onChangeOptions, items ] );

to something like this:

		const onChangeOptionsRef = useRef( onChangeOptions );
		onChangeOptionsRef.current = onChangeOptions;

		useLayoutEffect( () => {
			onChangeOptionsRef.current( items );
		}, [ items ] );

The reason I think this approach is preferable here is because, it should be AutocompleterUI's responsibility that its own effects work correctly. If we instead address it with a useCallback in the consumer, then all potential consumers will need to do the same thing, which is hard to know about.

I might be missing something though. What do you think?


function handleKeyDown( event ) {
backspacing.current = event.keyCode === BACKSPACE;