Skip to content

Commit

Permalink
replace useUpdateEffect implementations with useControlledValue
Browse files Browse the repository at this point in the history
  • Loading branch information
chad1008 committed Nov 28, 2022
1 parent a1e87ed commit 3acacad
Showing 1 changed file with 11 additions and 21 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@ import {
usePrevious,
useResizeObserver,
} from '@wordpress/compose';
import { forwardRef, useRef, useState, useMemo } from '@wordpress/element';
import { forwardRef, useRef, useMemo } from '@wordpress/element';

/**
* Internal dependencies
*/
import { View } from '../../view';
import ToggleGroupControlBackdrop from './toggle-group-control-backdrop';
import ToggleGroupControlContext from '../context';
import { useUpdateEffect } from '../../utils/hooks';
import { useControlledValue } from '../../utils/hooks';
import type { WordPressComponentProps } from '../../ui/context';
import type {
ToggleGroupControlMainControlProps,
Expand Down Expand Up @@ -49,35 +49,25 @@ function UnforwardedToggleGroupControlAsButtonGroup(
ToggleGroupControlAsButtonGroup,
'toggle-group-control-as-button-group'
).toString();
const [ selectedValue, setSelectedValue ] = useState( value );
const previousValue = usePrevious( value );

// Propagate selectedValue change.
useUpdateEffect( () => {
// Avoid calling onChange if selectedValue changed
// from incoming value.
if ( previousValue !== selectedValue ) {
onChange( selectedValue );
}
}, [ selectedValue, previousValue, onChange ] );

// Sync incoming value with selectedValue.
useUpdateEffect( () => {
if ( previousValue !== value ) {
setSelectedValue( value );
}
}, [ value, previousValue ] );
const [ selectedValue, setSelectedValue ] = useControlledValue( {
defaultValue: previousValue,
onChange,
value,
} );
// Expose selectedValue getter/setter via context
const groupContext: ToggleGroupControlContextProps = useMemo(
() => ( {
baseId,
state: selectedValue,
setState: setSelectedValue,
setState: setSelectedValue as React.Dispatch<
React.SetStateAction< string | number | undefined >
>,
isBlock: ! isAdaptiveWidth,
isDeselectable: true,
size,
} ),
[ baseId, selectedValue, isAdaptiveWidth, size ]
[ baseId, selectedValue, setSelectedValue, isAdaptiveWidth, size ]
);
return (
<ToggleGroupControlContext.Provider value={ groupContext }>
Expand Down

0 comments on commit 3acacad

Please sign in to comment.