Skip to content

4. Subscribe to specific state properties

Robin Karlsson edited this page Feb 21, 2023 · 1 revision

Subscribe to specific state properties: If your state object has many properties but you're only interested in changes to a specific subset of them, you can use a more targeted subscription approach. Instead of subscribing to the entire state object, you can subscribe to specific properties using a function that returns only the properties you care about. For example:

function subscribeToNameAndEmail(listener) {
  subscribe((state) => {
    listener({
      name: state.name,
      email: state.email,
    });
  });
}

This function subscribes to changes to the name and email properties of the state object, and calls the provided listener function with only those properties whenever they change.