No Time Dad

A blog about web development written by a busy dad

React Subscribe to State Changes

In my mind, the idea of “subscribing” to changes comes from Angular. Specifically, observables. A common pattern in Angular is to use something like myObservable.subscribe(...) to watch a value for changes, then do something based on the changes. I don’t think this pattern is as popular in React, but it’s definitely possible.

Click the button 3 times to see an alert.
Total clicks: 0
import React, { useState, useEffect } from 'react';

export const ButtonClicker = () => {
  const [clicks, setClicks] = useState(0);

  useEffect(() => {
    if (clicks === 3) alert("You've clicked the button 3 times!");
  }, [clicks]);

  return (
    <>
      Click the button 3 times to see an alert.
      <button onClick={() => setClicks(clicks + 1)} type="button">Click me!</button>
      Total clicks: {clicks}
      <button onClick={() => setClicks(0)} type="button">Reset</button>
    </>
  );
}

The idea here is that I’m using the React useEffect hook to watch the clicks state value for changes. The useEffect hook wraps React’s class based component methods componentDidMount, componentDidUpdate, and componentWillUnmount into a single function.

I’m essentially performing a sort of React subscribe when I pass the clicks value as the second argument to the useEffects function. Every time the clicks value changes, the if statement inside the hook is evaluated. Eventually, an alert will show up when the clicks count reaches three. This is how I say “React watch for changes”.

This is part of the reason that the hook is named useEffect. I’m essentially performing a side effect on each state value change, not directly effecting the clicks value. In Angular this would look something like the below with an observable subscribe to clicks.

clicks.subscribe(count => {
  if (count === 3) alert("You've clicked the button 3 times!");
});