Skip to content

Commit 464fef6

Browse files
committed
feat: useSessionStorage 커스텀 훅 추가
1 parent 5e4acfc commit 464fef6

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

src/hooks/useSessionStorage.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import { useState } from 'react';
2+
3+
const useSessionStorage = (key, initialValue) => {
4+
const [storedValue, setStoredValue] = useState(() => {
5+
try {
6+
const item = sessionStorage.getItem(key);
7+
return item ? JSON.parse(item) : initialValue;
8+
} catch (error) {
9+
console.error(error);
10+
return initialValue;
11+
}
12+
});
13+
14+
const setValue = (value) => {
15+
try {
16+
setStoredValue(value);
17+
sessionStorage.setItem(key, JSON.stringify(value));
18+
} catch (error) {
19+
console.error(error);
20+
}
21+
};
22+
23+
return [storedValue, setValue];
24+
};
25+
26+
export default useSessionStorage;

0 commit comments

Comments
 (0)