From 749a8843903c4ec0f56ccb07cea9e4a608688869 Mon Sep 17 00:00:00 2001 From: Marco Ciampini Date: Thu, 30 Nov 2023 22:22:18 +0100 Subject: [PATCH] Switch to new suggested implementation --- .../toggle-group-control/utils.ts | 41 ++++++++----------- 1 file changed, 16 insertions(+), 25 deletions(-) diff --git a/packages/components/src/toggle-group-control/toggle-group-control/utils.ts b/packages/components/src/toggle-group-control/toggle-group-control/utils.ts index cb97844c08a3a2..3f6d6e135a0df3 100644 --- a/packages/components/src/toggle-group-control/toggle-group-control/utils.ts +++ b/packages/components/src/toggle-group-control/toggle-group-control/utils.ts @@ -2,7 +2,7 @@ * WordPress dependencies */ import { usePrevious } from '@wordpress/compose'; -import { useEffect, useState } from '@wordpress/element'; +import { useEffect, useRef } from '@wordpress/element'; /** * Internal dependencies @@ -21,34 +21,25 @@ type ValueProp = ToggleGroupControlProps[ 'value' ]; export function useComputeControlledOrUncontrolledValue( valueProp: ValueProp ): { value: ValueProp; defaultValue: ValueProp } { - const [ - hasEverBeenUsedInControlledMode, - setHasEverBeenUsedInControlledMode, - ] = useState( false ); - const previousValueProp = usePrevious( valueProp ); + const prevValueProp = usePrevious( valueProp ); + const prevIsControlled = useRef( false ); + // Assume the component is being used in controlled mode on the first re-render + // that has a different `valueProp` from the previous render. + const isControlled = + prevIsControlled.current || + ( prevValueProp !== undefined && + valueProp !== undefined && + prevValueProp !== valueProp ); useEffect( () => { - if ( ! hasEverBeenUsedInControlledMode ) { - // Assume the component is being used in controlled mode if: - // - the `value` prop is not `undefined` - // - the `value` prop was not previously `undefined` and was given a new value - setHasEverBeenUsedInControlledMode( - valueProp !== undefined && - previousValueProp !== undefined && - valueProp !== previousValueProp - ); - } - }, [ valueProp, previousValueProp, hasEverBeenUsedInControlledMode ] ); + prevIsControlled.current = isControlled; + }, [ isControlled ] ); - let value, defaultValue; - - if ( hasEverBeenUsedInControlledMode ) { + if ( isControlled ) { // When in controlled mode, use `''` instead of `undefined` - value = valueProp ?? ''; - } else { - // When in uncontrolled mode, the `value` should be intended as the initial value - defaultValue = valueProp; + return { value: valueProp ?? '', defaultValue: undefined }; } - return { value, defaultValue }; + // When in uncontrolled mode, the `value` should be intended as the initial value + return { value: undefined, defaultValue: valueProp }; }