Created
July 16, 2022 01:10
-
-
Save itsMapleLeaf/bf2b0dbc24159bba787a7c3f28b9f336 to your computer and use it in GitHub Desktop.
have the thing exist immediately, but don't side effect on creation
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
function Example() { | |
const [store] = useState(() => createStore()) | |
useEffect(() => { | |
store.connect() | |
return () => store.disconnect() | |
}, [store]) | |
// do the thing with store, assuming it updates | |
} |
You can simply just do,
function Example() { const store = React.useRef(null); if (!store.current) { store.current = createStore() } }
This doesn't have a cleanup. We're not solving the problem of "create one store and never again", we're solving the problem of "my store does this side effect too many times", and the answer to that is an effect with a cleanup
If you create store once, you don't even need an cleanup.
It actually doesn't create the store once, it makes it twice under strict mode, and doesn't solve the issue Theo was having. See this here: https://codesandbox.io/s/sad-snow-pionqx
The side effect has to be moved out of render and into an effect with cleanup.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can simply just do,