Gathering detailed insights and metrics for tg-use-local-storage-state
Gathering detailed insights and metrics for tg-use-local-storage-state
Gathering detailed insights and metrics for tg-use-local-storage-state
Gathering detailed insights and metrics for tg-use-local-storage-state
React hook that persists data in localStorage
npm install tg-use-local-storage-state
Typescript
Module System
Min. Node Version
Node Version
NPM Version
TypeScript (84.33%)
JavaScript (15.6%)
Shell (0.07%)
Built with Next.js • Fully responsive • SEO optimized • Open source ready
Total Downloads
317,430
Last Day
20
Last Week
3,554
Last Month
13,783
Last Year
149,446
MIT License
328 Commits
2 Branches
1 Contributors
Updated on Mar 16, 2022
Latest Version
16.0.3
Package Id
tg-use-local-storage-state@16.0.3
Unpacked Size
39.06 kB
Size
8.57 kB
File Count
11
NPM Version
8.1.0
Node Version
16.13.0
Published on
Mar 07, 2023
Cumulative downloads
Total Downloads
Last Day
-86.7%
20
Compared to previous day
Last Week
0.1%
3,554
Compared to previous week
Last Month
-13.2%
13,783
Compared to previous month
Last Year
72.4%
149,446
Compared to previous year
27
tg-use-local-storage-state
This is a fork of https://github.com/astoilkov/use-local-storage-state that does 3 main things
isSimpleString
(default false) which simplifies the storage of simple string valuesReact hook that persist data in
localStorage
1npm install tg-use-local-storage-state
Window
storage
event and updates changes across browser tabs, windows, and iframe's.localStorage
throws an error and can't store the data. Provides a isPersistent
API to let you notify the user their data isn't currently being stored.1import useLocalStorageState from 'tg-use-local-storage-state' 2 3export default function Todos() { 4 const [todos, setTodos] = useLocalStorageState('todos', { 5 ssr: true, 6 defaultValue: ['buy avocado', 'do 50 push-ups'], 7 }) 8}
You can experiment with the example here.
1import React, { useState } from 'react' 2import useLocalStorageState from 'tg-use-local-storage-state' 3 4export default function Todos() { 5 const [todos, setTodos] = useLocalStorageState('todos', { 6 ssr: true, 7 defaultValue: ['buy avocado'], 8 }) 9 const [query, setQuery] = useState('') 10 11 function onClick() { 12 setQuery('') 13 setTodos([...todos, query]) 14 } 15 16 return ( 17 <> 18 <input value={query} onChange={(e) => setQuery(e.target.value)} /> 19 <button onClick={onClick}>Create</button> 20 {todos.map((todo) => ( 21 <div>{todo}</div> 22 ))} 23 </> 24 ) 25}
You can experiment with the example here.
1import React, { useState } from 'react' 2import useLocalStorageState from 'tg-use-local-storage-state' 3 4export default function Color() { 5 const [color, setColor] = useLocalStorageState('color', { 6 isSimpleString: true, 7 defaultValue: 'blue', 8 }) 9 10 return ( 11 <> 12 <button 13 onClick={function onClick() { 14 setColor('newColor') 15 }} 16 > 17 Set new color via hook 18 </button> 19 <button 20 onClick={function onClick() { 21 setColor('newColorFromLocalStorage') 22 }} 23 > 24 Set new color just by updating localstorage (not necessarily recommended but this 25 will work) 26 </button> 27 <div>{color}</div> 28 </> 29 ) 30}
You can experiment with the example here.
1import React, { useState } from 'react' 2// import useLocalStorageState from 'use-local-storage-state' //tnr comment this line in and the following line out to see the difference between the two libraries 3import useLocalStorageState from 'tg-use-local-storage-state' 4 5localStorage.removeItem('color') 6localStorage.removeItem('name') 7localStorage.setItem('name', 'nameAlreadySetInLocalStorage') 8localStorage.removeItem('age') 9 10export default function MyComponent() { 11 const [color, setColor] = useLocalStorageState('color', { 12 defaultValue: `defaultColor`, 13 isSimpleString: true, 14 }) 15 const [name, setName] = useLocalStorageState('name', { 16 defaultValue: 'defaultName', 17 isSimpleString: true, 18 }) 19 const [jsonifiedString, setJsonifiedString] = useLocalStorageState('jsonifiedString', { 20 defaultValue: JSON.stringify('default jsonified string val'), 21 //note no isSimpleString here 22 }) 23 const [age, setAge] = useLocalStorageState('age') 24 const [notes, setNotes] = useLocalStorageState('notes', { 25 defaultValue: ['default', 'notes'], 26 }) 27 28 return ( 29 <div> 30 <button 31 onClick={() => { 32 localStorage.setItem('color', `colorFromLocalStorage`) 33 localStorage.setItem('age', 1) 34 localStorage.setItem( 35 'jsonifiedString', 36 JSON.stringify(`jsonifiedStringFromLocalStorage`), 37 ) 38 localStorage.setItem('name', `nameFromLocalStorage`) 39 localStorage.setItem( 40 'notes', 41 `['noteFromLocalStorage','anotherNoteFromLocalStorage' ]`, 42 ) 43 }} 44 > 45 click me to manually update localStorage 46 </button> 47 <button 48 onClick={() => { 49 setColor('colorFromHook') 50 setAge(11) 51 setJsonifiedString(JSON.stringify('jsonifiedStringFromHook')) 52 setName('nameFromHook') 53 setNotes(['noteFromHook', 'anotherNoteFromHook']) 54 }} 55 > 56 click me to update via use-local-storage-state hook 57 </button> 58 <br></br> 59 <br></br> 60 <h3>color from use-local: {color}</h3> 61 <div>localStorage.getItem("color"): {localStorage.getItem('color')}</div> 62 <br></br> 63 <br></br> 64 this was the old and IMO kind of dumb way to handle strings where you'd either need to 65 JSON.stringify or wrap the strings in ticks like so `"someString"` : 66 <h3>jsonifiedString from use-local: {jsonifiedString}</h3> 67 <div> 68 localStorage.getItem("jsonifiedString"): {localStorage.getItem('jsonifiedString')} 69 </div> 70 <h3>name from use-local: {name}</h3> 71 <div>localStorage.getItem("name"): {localStorage.getItem('name')}</div> 72 <h3> 73 age from use-local:{' '} 74 {age || 75 'tnrTodo - there should be an age here.. this was already broken though before I got here'} 76 </h3> 77 <div>localStorage.getItem("age"): {localStorage.getItem('age')}</div> 78 <h3>notes from use-local: {notes && notes.join(',')}</h3> 79 <div>localStorage.getItem("notes"): {localStorage.getItem('notes')}</div> 80 <br></br> 81 <br></br> 82 <br></br> 83 <AnothaComponent /> 84 </div> 85 ) 86} 87 88function AnothaComponent() { 89 const [int, setNewInt] = useState(1) 90 const [color, setColor] = useLocalStorageState('color', { 91 defaultValue: `defaultNestedColor`, 92 isSimpleString: true, 93 }) 94 const [name, setName] = useLocalStorageState('name', { 95 defaultValue: 'defaultNestedName', 96 isSimpleString: true, 97 }) 98 const [age, setAge] = useLocalStorageState('age', { 99 defaultValue: 40, 100 }) 101 const [notes, setNotes] = useLocalStorageState('notes', { 102 defaultValue: ['default', 'nestedNotes'], 103 }) 104 105 return ( 106 <div> 107 <h3>Nested Component</h3> 108 <button 109 onClick={() => { 110 localStorage.setItem('color', `colorFromLocalStorage2`) 111 localStorage.setItem('name', `nameFromLocalStorage2`) 112 localStorage.setItem('age', 2) 113 localStorage.setItem( 114 'notes', 115 `['noteFromLocalStorage2','anotherNoteFromLocalStorage2' ]`, 116 ) 117 }} 118 > 119 click me to manually update nested localStorage 120 </button> 121 <button 122 onClick={() => { 123 setColor('colorFromHook2') 124 setName('nameFromHook2') 125 setAge(22) 126 setNotes(['noteFromNestedHook', 'anotherNoteFromNestedHook']) 127 }} 128 > 129 click me to update via nested use-local-storage-state hook 130 </button> 131 <br></br> 132 <br></br> 133 <h3>color from use-local nested: {color}</h3> 134 <div>nested localStorage.getItem("color"): {localStorage.getItem('color')}</div> 135 <h3>name from use-local nested: {name}</h3> 136 <div>nested localStorage.getItem("name"): {localStorage.getItem('name')}</div> 137 <h3>age from use-local nested: {age}</h3> 138 <div>nested localStorage.getItem("age"): {localStorage.getItem('age')}</div> 139 <h3>notes from use-local nested: {notes && notes.join(',')}</h3> 140 <div>nested localStorage.getItem("notes"): {localStorage.getItem('notes')}</div> 141 </div> 142 ) 143}
SSR supports includes handling of hydration mismatches. This prevents the following error: Warning: Expected server HTML to contain a matching ...
. This is the only library I'm aware of that handles this case. For more, see discussion here.
1import useLocalStorageState from 'tg-use-local-storage-state' 2 3export default function Todos() { 4 const [todos, setTodos] = useLocalStorageState('todos', { 5 ssr: true, 6 defaultValue: ['buy avocado', 'do 50 push-ups'], 7 }) 8}
localStorage
isn't saving the data using the `isPersistent`
propertyThere are a few cases when localStorage
isn't available. The isPersistent
property tells you if the data is persisted in localStorage
or in-memory. Useful when you want to notify the user that their data won't be persisted.
1import React, { useState } from 'react' 2import useLocalStorageState from 'tg-use-local-storage-state' 3 4export default function Todos() { 5 const [todos, setTodos, { isPersistent }] = useLocalStorageState('todos', { 6 defaultValue: ['buy avocado'], 7 }) 8 9 return ( 10 <> 11 {todos.map((todo) => ( 12 <div>{todo}</div> 13 ))} 14 {!isPersistent && <span>Changes aren't currently persisted.</span>} 15 </> 16 ) 17}
localStorage
and resetting to the defaultThe removeItem()
method will reset the value to its default and will remove the key from the localStorage
. It returns to the same state as when the hook was initially created.
1import useLocalStorageState from 'tg-use-local-storage-state' 2 3export default function Todos() { 4 const [todos, setTodos, { removeItem }] = useLocalStorageState('todos', { 5 defaultValue: ['buy avocado'], 6 }) 7 8 function onClick() { 9 removeItem() 10 } 11}
useLocalStorageState(key, options?)
Returns [value, setValue, { removeItem, isPersistent }]
when called. The first two values are the same as useState()
. The third value contains two extra properties:
removeItem()
— calls localStorage.removeItem(key)
and resets the hook to it's default stateisPersistent
— boolean
property that returns false
if localStorage
is throwing an error and the data is stored only in-memorykey
Type: string
The key used when calling localStorage.setItem(key)
and localStorage.getItem(key)
.
⚠️ Be careful with name conflicts as it is possible to access a property which is already in localStorage
that was created from another place in the codebase or in an old version of the application.
options.defaultValue
Type: any
Default: undefined
The default value. You can think of it as the same as useState(defaultValue)
.
options.ssr
Type: boolean
Default: false
Enables SSR support and handles hydration mismatches. Not enabling this can cause the following error: Warning: Expected server HTML to contain a matching ...
. This is the only library I'm aware of that handles this case. For more, see discussion here.
These are the best alternatives to my repo I have found so far:
No vulnerabilities found.