react-localstorage-helper
Installation
npm install react-localstorage-helper --save
Or if you're using yarn:
yarn add react-localstorage-helper
Getting Started
Access localStorage easily inside your React component.
- Full support to use localStorage with new
React Hooks
⚓. - Listen to changes easily just by pass a
Callback function
🔉. - No need to worry about encoding data to
JSON
and decoding it back.
Usage
Function components (With Hooks) ⚓.
import useLocalStorage from 'react-localstorage-helper'; const App = const name setName = ; const isDark setIsDark = ; return <div => <h1>Hello! name</h1> <input = /> <input ='checkbox' = = /> </div> ;;
Class components (With Callback Function) 🔉.
import localStorage from 'react-localstorage-helper'; Component { ; thisstate = name: 'Somebody' isDark: false ; thisupdateName = ; thisupdateIsDark = ; } { return <div => <h1>Hello! thisstatename</h1> <input = /> <input ='checkbox' = = /> </div> ; }
Documentation
Class component:
thisupdateValue = ;
localStorage
function returns a function to update the value in the localStorage and triggers onValueChange
callback function.
Function component:
const value setValue = ;
useLocalStorage()
Hook returns a stateful value, and a function to update it.
During the initial render, the returned value (value
) will be the same as the value passed as the secound argument (initialState
) if there is no data stored in the localStorage.
Lazy initial value
The initialValue
argument is the value used during the initial render if there is no stored value in the localStorage. In subsequent renders, it is disregarded. If the initial value is the result of an expensive computation, you may provide a function instead, which will be executed only on the initial render:
Class component:
thisupdateValue = ;
Function component:
const value setValue = ;
Functional updates
If the new value is computed using the previous value, you can pass a function to setValue
. The function will receive the previous value, and return an updated value. Here’s an example:
Class component:
thisupdateTheme = ;this;
Function component:
const them setTheme = ; ;
Authors
- Yaman KATBY - Initial work - Website
See also the list of contributors who participated in this project.
License
This library is licensed under the MIT License - see the LICENSE.md file for details.