Skip to content

Instantly share code, notes, and snippets.

@a-x-
Last active November 13, 2018 11:08
Show Gist options
  • Save a-x-/23ff4ced27b2ae52cb4119d8add1a987 to your computer and use it in GitHub Desktop.
Save a-x-/23ff4ced27b2ae52cb4119d8add1a987 to your computer and use it in GitHub Desktop.
react hooks on getters/setters — useStateObj
import React from "react";
import ReactDOM from "react-dom";
import useStateObj from "use-state-obj";
function App() {
var state = useStateObj({a:1})
function handleClick() {
++state.a
}
return (
<div className="App">
<h1>Hello, {state.a}!</h1>
<h2>Start editing to see some magic happen!</h2>
<button onClick={ handleClick }>click</button>
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
function useStateObj(props) {
const props_ = Object.entries(props).reduce((res, [key, val]) => {
const [v, setV] = useState(val);
res[key] = { get: () => v, set: (v) => setV(v) };
return res;
}, {});
return Object.defineProperties({}, props_);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment