aboutsummaryrefslogtreecommitdiff
path: root/src/hooks
diff options
context:
space:
mode:
Diffstat (limited to 'src/hooks')
-rw-r--r--src/hooks/interval.js26
-rw-r--r--src/hooks/local.js31
2 files changed, 57 insertions, 0 deletions
diff --git a/src/hooks/interval.js b/src/hooks/interval.js
new file mode 100644
index 0000000..78f6e7b
--- /dev/null
+++ b/src/hooks/interval.js
@@ -0,0 +1,26 @@
+import { useEffect, useRef } from "react";
+
+const useInterval = (callback, interval, immediate) => {
+ const ref = useRef();
+ useEffect(() => {
+ ref.current = callback;
+ }, [callback]);
+
+ useEffect(() => {
+ let cancelled = false;
+
+ const fn = () => {
+ ref.current(() => cancelled);
+ };
+
+ const id = setInterval(fn, interval);
+ if (immediate) fn();
+
+ return () => {
+ cancelled = true;
+ clearInterval(id);
+ };
+ }, [interval, immediate]);
+ };
+
+ export default useInterval;
diff --git a/src/hooks/local.js b/src/hooks/local.js
new file mode 100644
index 0000000..4b6b2ca
--- /dev/null
+++ b/src/hooks/local.js
@@ -0,0 +1,31 @@
+import { useState } from "react";
+
+const useLocalStorage = (key, initialValue) => {
+ const [storedValue, setStoredValue] = useState(() => {
+ if (typeof window === "undefined") {
+ return initialValue;
+ }
+ try {
+ const item = window.localStorage.getItem(key);
+ return item ? JSON.parse(item) : initialValue;
+ } catch (error) {
+ console.warn(error);
+ return initialValue;
+ }
+ });
+ const setValue = (value) => {
+ try {
+ const valueToStore =
+ value instanceof Function ? value(storedValue) : value;
+ setStoredValue(valueToStore);
+ if (typeof window !== "undefined") {
+ window.localStorage.setItem(key, JSON.stringify(valueToStore));
+ }
+ } catch (error) {
+ console.log(error);
+ }
+ };
+ return [storedValue, setValue];
+}
+
+export default useLocalStorage;