|
| 1 | +# 0.2.40 |
| 2 | + |
| 3 | +**Core Changes** |
| 4 | + |
| 5 | +- Add `createLocalStorageState` and `createSessionStorageState`. Example usage: |
| 6 | + |
| 7 | +```tsx |
| 8 | +// src/context/sidebar-active.tsx |
| 9 | +import { createLocalStorageState } from 'foxact/create-local-storage-state'; |
| 10 | + |
| 11 | +const [useSidebarActive, useSidebarActiveValue] = createLocalStorageState( |
| 12 | + 'sidebar-active', // The localStorage key |
| 13 | + /** |
| 14 | + * The initial value to use if there is no item in the local storage with the provided key, |
| 15 | + * the undefined value will be used if no initial value is provided. |
| 16 | + * |
| 17 | + * Also, the initial value will also be used during the server-side rendering, see below. |
| 18 | + */ |
| 19 | + false, |
| 20 | + /** |
| 21 | + * Optional configuration object enables the customization of value serialization before it's stored in local storage. |
| 22 | + */ |
| 23 | + { |
| 24 | + // Optional, default to false. When set to "true", the value will be passed to the localStorage API as is. |
| 25 | + raw: false, |
| 26 | + // Optional, default to "JSON.stringify". Can only be specified when the "raw" is set to false (which is the default). |
| 27 | + serializer: JSON.stringify, |
| 28 | + // Optional, default to "JSON.parse". Can only be specified when the "raw" is set to false (which is the default). |
| 29 | + deserializer: JSON.parse, |
| 30 | + } |
| 31 | +); |
| 32 | + |
| 33 | +export { useSidebarActive, useSidebarActiveValue }; |
| 34 | +``` |
| 35 | + |
| 36 | +And now you can use the getter and setter hooks anywhere in your app: |
| 37 | + |
| 38 | +```tsx |
| 39 | +// src/components/sidebar.tsx |
| 40 | +import { memo } from 'react'; |
| 41 | +import { useSidebarActive, useSidebarActiveValue } from '../context/sidebar-active'; |
| 42 | + |
| 43 | +function Sidebar() { |
| 44 | + const [sidebarActive, setSidebarActive] = useSidebarActive(); |
| 45 | + // If you only need the value, you can use `useSidebarActiveValue` instead: |
| 46 | + const sidebarActive = useSidebarActiveValue(); |
| 47 | + |
| 48 | + return ( |
| 49 | + <div className={`sidebar ${sidebarActive ? 'active' : ''}`}> |
| 50 | + <button onClick={() => setSidebarActive(false)}>Close Sidebar</button> |
| 51 | + </div> |
| 52 | + ); |
| 53 | +} |
| 54 | + |
| 55 | +export default memo(Sidebar); |
| 56 | +``` |
| 57 | + |
| 58 | +See the documentation for more information. |
| 59 | + |
1 | 60 | # 0.2.39
|
2 | 61 |
|
3 | 62 | **Core Changes**
|
|
0 commit comments