Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/dashboard/src/hooks/use-dirty-state.ts
2500 views
1
/**
2
* Copyright (c) 2023 Gitpod GmbH. All rights reserved.
3
* Licensed under the GNU Affero General Public License (AGPL).
4
* See License.AGPL.txt in the project root for license information.
5
*/
6
7
import { useCallback, useState } from "react";
8
9
// a hook that tracks whether a value has been changed from its initial value
10
export const useDirtyState = <T>(initialValue: T): [T, (val: T, trackDirty?: boolean) => void, boolean] => {
11
const [value, setValue] = useState<T>(initialValue);
12
const [dirty, setDirty] = useState<boolean>(false);
13
14
// sets value, and by default sets dirty flag to true
15
// trackDirty can be optionally overridden to prevent setting the dirty flag
16
// this is useful for cases where a value needs to be updated, but not necessarily treat it as dirty
17
const setDirtyValue = useCallback((value: T, trackDirty = true) => {
18
setValue(value);
19
if (trackDirty) {
20
setDirty(true);
21
}
22
}, []);
23
24
return [value, setDirtyValue, dirty];
25
};
26
27