Skip to content

Commit

Permalink
Add useStickyState hook to utilities
Browse files Browse the repository at this point in the history
  • Loading branch information
campb303 committed Aug 2, 2021
1 parent 85f262d commit 82af2c6
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion src/utilities.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { useState, useEffect } from "react";

/**
* Returns true if object has no entries, otherwise false.
* @param {Object} objectToCheck The object to check.
Expand All @@ -7,4 +9,24 @@ function objectIsEmpty(objectToCheck) {
return Object.entries(objectToCheck).length === 0;
}

export { objectIsEmpty };
/**
* Returns value of key in localStorage or default value in state. The state and localStorage value are updated together.
* @param {*} defaultValue The value to use if no value for key exist in localStorage.
* @param {string} key The key to lookup in localStorage.
* @returns {Array} Getter and setter of state variable.
* @see https://reactjs.org/docs/hooks-state.html
*/
function useStickyState(defaultValue, key) {
const [value, setValue] = useState(() => {
const stickyValue = window.localStorage.getItem(key);
return stickyValue !== null
? JSON.parse(stickyValue)
: defaultValue;
});
useEffect(() => {
window.localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}

export { objectIsEmpty, useStickyState };

0 comments on commit 82af2c6

Please sign in to comment.