would lazy initialization of useState work as a useSingleton e.g.
useSingleton
const useSingleton = (initializer) => { React.useState(initializer) } const Foo = () => { useSingleton(() => { // only runs once }) ... }
Yep. That works as well!
A more fleshed out example:
// custom hook "use initializer" function useInit(init, ...args) { const tuple = useState(null); const [state, setState] = tuple; if(state !== null) { return tuple; } const initState = init(setState, ...args); setState(initState); return [initState, setState]; } // Component Parts function initCounter(setState, startAt) { const increment = state => ({...state, count: state.count + 1}); const clickHandler = () => setState(increment); return { count: Number(startAt), clickHandler }; } // Component function Counter({startAt}) { const [{count, clickHandler}, setState] = useInit(initCounter, startAt); return html` <p> <button onClick=${clickHandler}>Click me</button> </p> <output>You clicked ${count} times</output> `; } function App() { return html`<${Counter} startAt="12" />`; }
Gist
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
would lazy initialization of useState work as a
useSingleton
e.g.
Yep. That works as well!
A more fleshed out example:
Gist