Path: blob/main/components/dashboard/src/hooks/use-dirty-state.ts
2500 views
/**1* Copyright (c) 2023 Gitpod GmbH. All rights reserved.2* Licensed under the GNU Affero General Public License (AGPL).3* See License.AGPL.txt in the project root for license information.4*/56import { useCallback, useState } from "react";78// a hook that tracks whether a value has been changed from its initial value9export const useDirtyState = <T>(initialValue: T): [T, (val: T, trackDirty?: boolean) => void, boolean] => {10const [value, setValue] = useState<T>(initialValue);11const [dirty, setDirty] = useState<boolean>(false);1213// sets value, and by default sets dirty flag to true14// trackDirty can be optionally overridden to prevent setting the dirty flag15// this is useful for cases where a value needs to be updated, but not necessarily treat it as dirty16const setDirtyValue = useCallback((value: T, trackDirty = true) => {17setValue(value);18if (trackDirty) {19setDirty(true);20}21}, []);2223return [value, setDirtyValue, dirty];24};252627