Created
October 27, 2018 08:15
-
-
Save stigi/3d0f9b26b6bde0da5b855ea18b696e2c to your computer and use it in GitHub Desktop.
A small experiment on how a persisted state hook good be implemented
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 ReactDOM from "react-dom"; | |
const usePersistedState = (initialState, key) => { | |
// Check if we have a value stored | |
let value = localStorage.getItem(key); | |
if (!value) { | |
value = initialState; | |
} else { | |
value = JSON.parse(value); | |
} | |
const [state, setState] = useState(value); | |
const newSetState = newValue => { | |
localStorage.setItem(key, JSON.stringify(newValue)); | |
setState(newValue); | |
}; | |
return [state, newSetState]; | |
}; | |
const App = () => { | |
const [count, setCount] = usePersistedState(0, "myKey"); | |
return ( | |
<div> | |
<h1>Hello</h1> | |
<p>{`You've clicked ${count} times`}</p> | |
<button | |
onClick={() => { | |
setCount(count + 1); | |
}} | |
> | |
Click Me | |
</button> | |
</div> | |
); | |
}; | |
ReactDOM.render(<App />, document.getElementById("app")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment