From 10638e350fb81d257f26b7c8fa2b134e75251cb5 Mon Sep 17 00:00:00 2001 From: Claire Date: Thu, 13 Mar 2025 12:27:49 +0100 Subject: [PATCH] Streamline state/ref synchronization --- .../account/components/account_note.tsx | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/app/javascript/mastodon/features/account/components/account_note.tsx b/app/javascript/mastodon/features/account/components/account_note.tsx index cc8b97681b..b304e667b1 100644 --- a/app/javascript/mastodon/features/account/components/account_note.tsx +++ b/app/javascript/mastodon/features/account/components/account_note.tsx @@ -55,19 +55,8 @@ const InnerAccountNote: React.FC = ({ accountId }) => { const [value, setValue] = useState(initialValue ?? ''); const [saved, setSaved] = useState(false); - // We need to access the value on unmount - const valueRef = useRef(value); const dirtyRef = useRef(false); - // Keep the valueRef in sync with the state - useEffect(() => { - valueRef.current = value; - }, [value]); - - useEffect(() => { - if (initialValue !== valueRef.current) setValue(initialValue ?? ''); - }, [initialValue, setValue]); - useEffect(() => { dirtyRef.current = initialValue !== undefined && initialValue !== value; }, [initialValue, value]); @@ -84,13 +73,6 @@ const InnerAccountNote: React.FC = ({ accountId }) => { [accountId, dispatch, setSaved], ); - // Save changes on unmount - useEffect(() => { - return () => { - if (dirtyRef.current) onSave(valueRef.current); - }; - }, [onSave]); - const handleChange = useCallback>( (e) => { setValue(e.target.value); @@ -120,6 +102,24 @@ const InnerAccountNote: React.FC = ({ accountId }) => { if (dirtyRef.current) onSave(value); }, [onSave, value]); + // To save the changes on unmount, we need to synchronize the state in a ref + const valueRef = useRef(value); + + useEffect(() => { + valueRef.current = value; + }, [value]); + + useEffect(() => { + return () => { + if (dirtyRef.current) onSave(valueRef.current); + }; + }, [onSave]); + + // Handle `initialValue` changes + useEffect(() => { + if (initialValue !== valueRef.current) setValue(initialValue ?? ''); + }, [initialValue, setValue]); + return (