---
name: Window subscriptions
menu: Patterns
parent: Utils
---

# Window subscriptions

This is a non visual pattern for enabling other patterns to respond to global page events.

## Implementation

```tsx
import { WindowSubscriptionsContext } from '../../../../Sticky';

export class SubsciptionConsumer extends React.Component {
  subscribed = false;
  unsubscribe?: (handler: () => void) => void;

  handler = () => {
    // handle events
  };

  componentWillUnmount() {
    // this should only get hit if we are unsubscribing before we have finished a render
    // probably not possible
    if (this.unsubscribe) {
      this.context.unsubscribe(this.handler);
    }
  }
  render() {
    return (
      <WindowSubscriptionsContext.Consumer>
        {value => {
          if (this.subscribed === false) {
            value.subscribe(this.handler);
            this.unsubscribe = value.unsubscribe;
            this.subscribed = true;
          }

          return <div />;
        }}
      </WindowSubscriptionsContext.Consumer>
    );
  }
}
```
