1. 22
    Redux: Extracting Container Components (FilterLink)
    8m 4s

Redux: Extracting Container Components (FilterLink)

Dan Abramov
InstructorDan Abramov
Share this video with your friends

Social Share Links

Send Tweet
Published 9 years ago
Updated 4 years ago

Learn how to avoid the boilerplate of passing the props down the intermediate components by introducing more container components.

[00:00] In the previous lesson, we separated the presentational components from the main container component. The to-do app specifies the behaviors, which is what happens when add button, how the to-dos are selected, what happens when a single to-do is being clicked, and what happens when a footer link is clicked.

[00:19] The components, such as at to-do, the to-do list, the to-do itself, the footer, and the filter link, they don't dispatch actions. They call their callbacks in the props. They are only responsible for the looks but not for the behavior.

[00:39] The downside of this approach is that I have to pass a lot of props down the tree even when the intermediate components don't really use them.

[00:48] For example, the filter link needs to know the current filter so that it can choose a different appearance when it is active. However, in order to receive the current filter, it has to be passed down from the top. This is why the footer has to accept visibility filter as a prop, so it can pass it down as a current filter to the filter link.

[01:10] In a way, this breaks encapsulation because the parent components need to know too much about what data the child components need. To solve this, we're going to extract a few more container components, just like we extracted the presentation components in the previous lesson.

[01:29] The first component I'm going to refactor is the footer component. Currently, it accepts two props -- the visibility filter, and the on filter click callback. But it doesn't actually use either of them. It just passes them down to the filter link. This seems like a good opportunity for simplification.

[01:50] We can only do this because we know that the footer component doesn't care about the values of these props. They only exist to be passed down to the filter link that cares about them.

[02:01] I am removing the props definition, and I'm removing these props from the filter link usage. It might start to seem a lot like the the code before separating the presentational component. However, what I want to here is a little bit different.

[02:19] The filter link does not currently specify the behavior for clicking on the link. It also needs the current filter to tell whether it should be rendered as active.

[02:30] Therefore, it's a bit dishonest to say that filter link is a presentational component because it is inseparable from its behavior. The only reasonable reaction to clicking on it is setting the visibility filter by dispatching an action.

[02:46] This is why I'm changing it to a different presentational component I'm going to call, "link." I will create another filter link component as a container that uses it for rendering. The link component doesn't know anything about the filter. It only accepts the active prop, and it calls its own click handler. It is only concerned with rendering.

[03:10] However, I'm also creating another component, called, "filter link." It is going to be a class this time that is going to render the link with the current data from this chore. It's going to read the component props, and it's going to read the state. But I don't mean react state. I mean the Redux chore state it gets by calling, "store get state."

[03:33] As a container component, the filter link doesn't have its own markup. It delegates rendering to the link presentational component. In this case, it calculates its active prop by comparing its own filter prop with the visibility filter in the Redux chore state. The filter prop is the one that is passed to the filter link from the footer. The visibility filter corresponds to the currently chosen visibility filter that is held in Redux chore state. If they match, we want the link to appear active.

[04:09] The container component also needs to specify the behavior. In this case, the filter link specifies that when this particular link is clicked, we should dispatch the action with the type set visibility filter and the filter value that we take from the props.

[04:27] The filter link may accept children which are used as the contents of the link, so we're going to pass the children down to the link component. We're just going to render them inside the A tack.

[04:39] There is a small problem with this implementation of filter link. Inside the render map, it reads the current state of the Redux chore. However, it does not subscribe to this chore. If the parent component does not update when this chore is updated, it's going to render this tail value.

[04:58] Currently, we rearrange the whole application when the state changes. However, this is not very efficient. In future, we will instead move subscription to this chore, to the lifecycle methods of the container components.

[05:14] React provides a special force update method on the component instances to force their re-rendering. We're going to use it together with chore subscribe method so that any time the store state changes, we force update the container components.

[05:30] We perform the subscription inside the component if mount lifecycle method. So it's important to unsubscribe inside the component will unmount method. Note that we don't actually have the unsubscribe function, but this is the return value of the store subscribe method, so we can keep it, and then call it inside component will unmount.

[05:54] Let's recap this part. The filter link component subscribes to this chore, calling force update any time this chore changes so it can render the current state of this chore. It saves the reference through the unsubscribe function returned by store subscribe. It invokes it when the component is about to unmount to clean up the subscription.

[06:17] Let's recap the relationship between the filter link container component and the link presentational component. The link component only specifies the appearance of the the link, when it is active or inactive, but it doesn't know about the behavior. The filter link component is a container, so it provides the data and the behavior for the presentational component.

[06:43] When it mounts, it subscribes to this chore, so it independently re-renders when the store state changes because it needs to use this chore current state inside its render method.

[06:55] Instead of specifying the DOM tree, it delegates all the rendering to the link presentational component. Its only job is to calculate the props based on the filter link's own props and the current state of the Redux chore. It also specifies the callbacks that are going to dispatch the actions on this chore.

[07:17] After the action is dispatched, this chore will remember the new state returned by the reducer and will call every subscriber to this chore. In this case, every filter link component instance is subscribed to this chore, so they will all have their force update methods called on them. They will re-render according to the current chore state.

[07:41] The filter link is a container component, so it is completely self-sufficient and can be used inside the presentational components, such a footer, without passing additional props to get the data from this chore and specify the behavior. This lets us keep the footer component simple and decoupled from the behavior and the data that its child components need.

Anda Pop
Anda Pop
~ 9 years ago

If the parent component does not update when the store updates, then FilterLink will re-render with a stale value

It's probably a mistake on my part to wrap my head around this without hands on experience, but I do have a question: When would not updating the parent component, be of consequence to the FilterLink (a child component)? Can you please give me an example?

Lars Jägare
Lars Jägare
~ 9 years ago

Up to this point the tutorial is excellent, but I have a problem with this lesson. The FilterLink component in this lesson is not following the rules in React. This error is removed in later chapters and is not the way things are done in Redux, so it is just confusing. And it is not needed in order to get an understanding of how things are done in Redux either.

Let me explain the problem:

The contract of a a react component is that the result returned from render should only depend on this.state and this.props and nothing else. See the component spec

In this lesson we have for FilterLink

render() { const state = store.getState() and then state.visibilityFilter() is used when setting up the returned Link element. That is, render() depends on something else than this.state or this.props which is simply illegal in React.

The proper way to do this is to use this.state instead. This is done by reading the value from store.getState() in the subscribe listener and call this.setState() of the component.

componentDidMount() { this.unsubscribe = store.subscribe(() => this.setState({visibilityFilter: store.getState().visibilityFilter}); ... render() { const state = this.state; // NB No access of store here! When done this way the forceUpdate call is not needed, since re-rendering will be triggered properly through setState.

Here is a JSBIN with this modification

Lars Jägare
Lars Jägare
~ 9 years ago

Here is an [example] (http://jsbin.com/kuboqi/edit?html,js,output) where the parent component gets re-rendered but the children don't. In essence this depends on the optimizations in the implementation of React rendering. It assumes the components follow the contract: if props and state are unchanged render should return the same thing, so calls to render can be optimized away. Exactly how this is done is an implementation detail and not specified. But it's not a problem: as long as your components follow the contract they will be re-rendered properly. (Then, if you don't break things, you don't need to worry how to fix it again)

[Here] (https://github.com/facebook/react/issues/4067) is a discussion where Sebastian Markbåge make some good clarifications on this topic.

Dan Abramov
Dan Abramovinstructor
~ 9 years ago

This tutorial is just an approximation of how connect() from React Redux works. Please watch series to the end, which is where we start using it and remove the “wrong” code. Technically connect() uses setState() but this is irrelevant implementation detail to this tutorial which is why I went with forceUpdate(). It really doesn't matter because this code is temporary and is later changes to use connect() instead.

Sequoia McDowell
Sequoia McDowell
~ 9 years ago

I'm confused about the use of props.filter here. It seems like filter should be an explicitly defined argument to the FilterLink "constructor", instead it's not explicitly defined as a required property but it is implicitly relied upon. How are users of FilterLink to know which props they should set on it, which it supports and which are required?

Sequoia McDowell
Sequoia McDowell
~ 9 years ago

I'd love to see this intermediate impl (using react state) between the quick-and-dirty impl here and the final black-box connect impl. Lars's comment mostly covers it I guess :)

Dan Abramov
Dan Abramovinstructor
~ 9 years ago

How are users of FilterLink to know which props they should set on it, which it supports and which are required?

Usually people define propTypes on the component. They serve as a kind of documentation. You can define propTypes on the component returned by connect() too.

Dan Abramov
Dan Abramovinstructor
~ 9 years ago

I'd love to see this intermediate impl (using react state) between the quick-and-dirty impl here and the final black-box connect impl. Lars's comment mostly covers it I guess :)

I tried it at first but it made things super confusing because the word “state” now refers to completely different things: React state (an implementation detail) and Redux state (the thing we’re trying to teach). It’s so easy to confuse one for the other so I decided not to mention React state at all, especially considering that this hack is going away in the next lessons.

Bogdan Bivolaru
Bogdan Bivolaru
~ 8 years ago

In my Moz FF49 browser FilterLink is re-rendered anyway along just as the rest of the application, componentDidMount and componentWillUnmount do not get called at all. So I'm not sure I understand your point - why use componentDidMount at all?

Is this just a place to explain updates between Redux store and React?

Kushal Mahajan
Kushal Mahajan
~ 8 years ago

I didn't see any difference of using the below code. For me it worked same with or without.

 componentDidMount(){
    this.unsubscribe = store.subscribe(() => {
        this.forceUpdate();
    });
}

componentWillUnmount(){
    this.unsubscribe();
}
dan entous
dan entous
~ 7 years ago

as far as i understand it ...

in this lesson, dan reminds us that the entire app is subscribed to the store with the line store.subscribe( render ). because any change in the app will update all components the FilterLink code change doesn’t create any noticeable change - thus you can comment out the componentDidMount and componentWillUnmount without any change in how the application works.

but this lesson only begins the process of extracting the components, so if you comment out the subscription, store.subscribe( render ), it will break the app - partially. the FilterLink will continue to work, but adding todos will not.

in the next lesson, dan finishes the component extraction and is then able to remove the store.subscribe( render ). each container component subscribes itself, individually, to the store so the app, as a whole, no longer needs to subscribe to the store. if you comment out the componentDidMount lines at that point, then you’ll see the “stale” state that he mentions in this video.

Markdown supported.
Become a member to join the discussionEnroll Today