from Hacker News

Use a Render Prop

by freeman478 on 11/8/17, 12:41 PM with 33 comments

  • by wereHamster on 11/9/17, 7:07 PM

    People seem to forget that components (stateless components, stateless functional components or whatever you want to call them) are just functions. One function calls another function, that's function composition. In plain JavaScript we do it all the time. But when React is involved people are suddenly all like: no you can't call that function directly, you have to name it 'Component' with a capital C and use like '<Component />' and to compose two Components you have to use a HOC. It's like they all forget how to JavaScript…
  • by pspeter3 on 11/9/17, 3:26 PM

    As a note, it is not safe for a component using a render prop to implement shouldComponentUpdate. The problem is that the render prop may close over data that the component is unaware of. The Asana core components used to the use the render prop pattern until we discovered that issue and also realized it made tests harder to write. Now we use React.cloneElement instead.
  • by catpolice on 11/9/17, 11:52 PM

    I started today by setting out to write a response of the form "Certainly you couldn't rewrite MY HOC library to use render props, look at how it [etc]" and ended today having rewritten my HOC library to use render props. In the process, I was able to dramatically simplify the API and remove about a third of the overall code.

    So, uh, thanks.

  • by couchand on 11/9/17, 5:13 PM

    This technique is very useful, but passing the callback as a prop is an ugly way to do it. Much cleaner to pass the callback as children [0].

    Then, the final example looks like:

      <Mouse>
        {({ x, y }) => (
          <h1>The mouse position is ({x}, {y})</h1>
        )}
      </Mouse>
    
    [0]: https://discuss.reactjs.org/t/children-as-a-function-render-...
  • by arenaninja on 11/9/17, 8:04 PM

    My biggest issue with HOCs is the hard time you have when things are nested to high hell. A component like withThis(withThat(enrich(withState(withPropsOnChange(withPropsOnChange(withPropsOnChange(withPropsOnChange(....... when this component gives you an issue you begin to wonder what HOCs are really doing for you.

    Having a render prop is slightly better but even this escape hatch isn't foolproof and you'll still end up needing things like onClickOutside.

  • by reichardt on 11/9/17, 10:02 AM

    Neat! Didn't know about this concept. Any more examples of this being used somewhere?
  • by hguhghuff on 11/9/17, 3:19 PM

    What would the code look like to use this approach for Redux.

    Could Redux boilerplate be reduced?

  • by tootie on 11/9/17, 2:10 PM

    Even using the term "higher order" that seems like a very OOP solution, while render props is very functional and thus a better idiom for JavaScript.