Write Channels as Components

Learn how to write channels as components.

We'll cover the following

Components

Components are the heart of React. The type of component that we’re most familiar with is a presentation component—this type of component renders the user interface and accepts input events from the user. Components do not need to have an interface, though. A container component can wire up logic, configure other components, pull data from other sources, or set up a context.

We use container components to separate the Phoenix code from the rest of the application. Without this separation, we could get by adding Channels directly into a presentation component, but the lack of separation becomes hard to maintain and grow over time. Use components to create an application that is easy to change and understand.

There’s an easy way to tell if our application’s components are doing too much. If a component defines the Socket or Channel in the same component that renders the interface, then we may benefit by splitting the Socket or Channel into separate components. In general, it’s a best practice to have single-purpose components that each perform a single task.

A simple example

For example, imagine an ActivityFeedPage component that renders timeline data in real-time. We might implement the component with the following code.

Get hands-on with 1000+ tech skills courses.