Created
November 1, 2020 15:10
-
-
Save Rigel772/9bbf9c7abe8e213b75d2896ecbae6070 to your computer and use it in GitHub Desktop.
[custom hooks - useLocalStorage] #react
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { useState } from 'react' | |
| import useLocalStorage from './useLocalStorage' | |
| import useUpdateLogger from './useUpdateLogger' | |
| function App() { | |
| const [name, setName] = useLocalStorage('name', '') | |
| useUpdateLogger(name) | |
| return ( | |
| <div> | |
| <h1>Hello</h1> | |
| <input | |
| type='text' | |
| value={name} | |
| onChange={(e) => setName(e.target.value)} | |
| /> | |
| </div> | |
| ) | |
| } | |
| export default App |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { useState, useEffect } from 'react' | |
| function getValue(key, initValue) { | |
| const savedValue = JSON.parse(localStorage.getItem(key)) | |
| if (savedValue) return savedValue | |
| if (initValue instanceof Function) return initValue() | |
| return initValue | |
| } | |
| export default function useLocalStorage(key, initValue) { | |
| const [value, setValue] = useState(() => { | |
| return getValue(key, initValue) | |
| }) | |
| useEffect(() => { | |
| localStorage.setItem(key, JSON.stringify(value)) | |
| }, [value]) | |
| return [value, setValue] | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { useEffect } from 'react' | |
| export default function useUpdateLogger(value) { | |
| useEffect(() => { | |
| console.log(value) | |
| }, [value]) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment