Skip to content

Instantly share code, notes, and snippets.

@itsMapleLeaf
Created July 16, 2022 01:10
Show Gist options
  • Save itsMapleLeaf/bf2b0dbc24159bba787a7c3f28b9f336 to your computer and use it in GitHub Desktop.
Save itsMapleLeaf/bf2b0dbc24159bba787a7c3f28b9f336 to your computer and use it in GitHub Desktop.
have the thing exist immediately, but don't side effect on creation
function Example() {
const [store] = useState(() => createStore())
useEffect(() => {
store.connect()
return () => store.disconnect()
}, [store])
// do the thing with store, assuming it updates
}
@kristersd
Copy link

kristersd commented Jul 16, 2022

You can simply just do,

function Example() {
  const store = React.useRef(null);
 
  if (!store.current) {
    store.current = createStore()
  }
}

@itsMapleLeaf
Copy link
Author

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

@kristersd
Copy link

If you create store once, you don't even need an cleanup.

@itsMapleLeaf
Copy link
Author

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