Skip to content

watch

Method to watch for state changes and execute side effects.

Description

The watch method allows you to subscribe to state changes and execute side effects when the state updates. Unlike use, this doesn't trigger component re-renders but instead runs the provided callback function whenever the state changes.

Input/Output

InputTypeDescription
callback(value: T) => voidFunction to execute when state changes
depsDependencyList (optional)Dependency array for when to re-subscribe
OutputTypeDescription
ReturnsvoidNo return value

Example

typescript
import { signify } from "react-signify";
import { useEffect } from "react";

const sCounter = signify(0);
const sUser = signify({ name: "John", age: 25 });

function MyComponent() {
  // Watch counter changes
  sCounter.watch((newValue) => {
    console.log("Counter changed to:", newValue);
    if (newValue > 10) {
      alert("Counter exceeded 10!");
    }
  });

  // Watch user changes with dependencies
  sUser.watch((newUser) => {
    localStorage.setItem("user", JSON.stringify(newUser));
  }, []);

  return (
    <div>
      <button onClick={() => sCounter.set(sCounter.value + 1)}>
        Increment
      </button>
    </div>
  );
}

Released under the MIT License.