'Avoid useState hook to run on initialisation

I have a simple button, which subscribes and unsubscribes onPress()

<Button
      onPress={() => setRunning(running => !running)}
      title={running ? 'Stop' : 'Start'}
/>

But when I initialise my state, it runs the useState function which is fatal, because I can't unsubscribe from something I haven't been subscribed too.

const [running, setRunning] = useState(false);

useState(() => {
  if (running) {
    subscription.subscribe(...)
  } else {
    subscription.unsubscribe();
  }
});

how can I avoid that useState ran unless I pressed the button?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source