Answers to common questions about the render prop template

Original author: Kent C. Dodds
  • Transfer
Kent S. Dodds, the author of the material we are publishing today, says that recently a group of programmers with whom he was supposed to conduct a React training became interested in the “render props” template, which is also called the “function as a descendant” template (in different in publications he is referred to as “children as a function” or “function as child”). The React documentation defines render prop as a simple technique for passing code between React components using a property whose value is a function. A component using render prop accepts a function that returns a React element. This component calls this function instead of implementing its own rendering logic. Kent recommends reading this material for anyone new to the render prop template.and watch this video , and then read on. Kent says that in preparation for the classes, he experimented and decided to ask his readers on Twitter what questions they have about render props, about the details of what other templates related to this, they would like to know, and about what examples would help them with render props figure it out. Kent received a lot of feedback in response to his tweet. As a result, he decided to dwell on the three most typical questions regarding the render prop template and answer them, illustrating the answers with examples.

image



Question # 1: How does using the render prop template affect performance?


Perhaps this is the very question that most often arises when I talk about the render prop template. In addition, in the comments to the aforementioned tweet several times they asked specifically about performance. My answer to this question is very simple. Here I refer to Ryan Florence's material on the use of functions and performance in React. If we quote the main conclusions of this material, we can say the following:

  • Write the code as you used to, realizing your ideas in it.
  • Take performance measurements to find bottlenecks. Here you can learn how to do it.
  • Use PureComponentand shouldComponentUpdateonly when necessary, skipping functions that are component properties (only if they are not used in lifecycle event hooks to achieve side effects).

If you are opposed to premature optimization, then you don’t need proof that the built-in features degrade performance. You, in order to think about their optimization, need evidence to the contrary.

I would like to supplement these conclusions. If you are really worried about embedding render prop-functions and the possible negative impact of this on performance - just do not use the built-in functions.

class MyComp extends React.Component {
  renderDownshift = downshift => (
    
{/* Элементы пользовательского интерфейса */}
 )  render() {    return (              {this.renderDownshift}          )  } }

Question # 2: How, when using render props, avoid overly complicated rendering code that is hard to read?


One of my readers, Mark Erickson, asked a question about how to use the template render props, not to put all the rendering logic of nested functions inside the method render(). He wanted to know if, for the sake of increasing code readability, it is possible to break this logic into small functions, but at the same time not to refuse render props.

Mark asks the right questions. Almost all the examples of using the render prop template that I have ever seen come down to placing all the rendering logic in one function. Usually in such cases, you can see the return command and one gigantic expression. These huge rendering functions annoyed me, but I began to relate to them much better when I realized that the only reason I didn’t like them was because I thought they were complicated, although in reality it’s not. .

In any case, since what we call "render props" are just functions that are called with arguments, you can do whatever you like with them. As a result, I prepared a couple of examples for Mark .


Examples for Mark

Here is a shortened version of the code for these examples.

function JustARegularFunctionComponent(props) {
  // тут можете делать что хотите
  return 
{/* ваш код */}
} function App() {  return (    
     
       With a totally different component.        Thanks React composibility!      
      (                  )}      />      
     
       Inline! You don't have to make it an        implicit return arrow function      
      { // <-- notice the curly brace!          // тут можете делать что хотите          return
{/* ваш код */}
       }}      />    
 ) }

Question No. 3: How to organize access to the arguments of render prop-functions in the methods of processing events of the component life cycle?


Another fairly common question is how to access the arguments to the render prop function in the methods for processing the component life cycle. The difficulty here is that these functions are called in the context of the rendercomponent, so it is unclear how to work with the data transmitted to them, say, in componentDidMount.

In fact, the answer to this question is hidden in the answer to Mark's question, which we examined above. Please note that due to React's compositional capabilities, we can create a separate component and simply redirect the arguments to the properties of our component. For example, you can do this .

class RegularClassComponent extends React.Component {
  componentDidUpdate() {
    // вот то, что вам нужно
    console.log(this.props.whatever)
  }
  render() {
    return 
{/* код пользовательского интерфейса */}
 } } function App() {  return (    }    />  ) }

My friend Donavon will be saddened if I don’t talk about his favorite component injection pattern . Using this template to achieve our goal can be even easier, and the code will look cleaner:

class RegularClassComponent extends React.Component {
  componentDidUpdate() {
    // вот то, что вам нужно
    console.log(this.props.whatever)
  }
  render() {
    return 
{/* код пользовательского интерфейса */}
 } } function App() {  return (      ) }

You can work on the implementation details yourself. Alternatively, take a look at the new library that Donavon created after our talk about render props.

Summary


I believe that the render prop template is just a great technology, and I look forward to adding to the awesome-react-render-props list that Jared Palmer is working on . In this template, I especially like the fact that it can include the logic of the component and at the same time not harm the system's configuration capabilities and not complicate the markup. I think that with regard to render props, we still have a lot of interesting things to do.

Dear readers! Do you use the render props template in your React projects?

Also popular now: