Skip to content

Instantly share code, notes, and snippets.

@stigi
Created October 27, 2018 08:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stigi/3d0f9b26b6bde0da5b855ea18b696e2c to your computer and use it in GitHub Desktop.
Save stigi/3d0f9b26b6bde0da5b855ea18b696e2c to your computer and use it in GitHub Desktop.
A small experiment on how a persisted state hook good be implemented
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