First, this is not about if
in JSX. It's just the simplest example
to talk about (and a lot of people tried to do it at first a long
time ago).
Some react components conditionally render content. When React first
went public, a lot of us coming from handlebars really wanted "if"
syntax. This gist isn't just about If
components though, it's about
any component that has an API that conditionally renders stuff.
And so we made stuff like this:
<If cond={stuff}>
<div>Thing<Div>
</If>
And then <If>
was implemented like so:
const If = ({ cond, children }) => (
cond ? children : null
)
Works great, but there's a performance issue, every render you are
calling createElement
on the div
. Remember, JSX transpiles to this:
React.createElement(
If,
{ cond: stuff },
React.createElement(
'div',
null,
'Thing'
)
)
So every render we're calling createElement('div')
even though it
never gets rendered. For small bits of UI, this isn't really a problem,
but it's common for a large portion of your app to be hiding
conditionally behind that If
.
So, when you've got a component that conditionally renders some of the children it was passed, consider using a render callback instead:
<If cond={stuff}>
{() => (
<div>Thing</div>
)}
</If>
And then If
looks like this:
const If = ({ cond, children }) => (
cond ? children() : null // called as a function now
)
This is good because now we aren't calling createElement('div')
unless
it's actually rendered.
Again, not a big deal in small cases, but for something like React Router Match
or React Media, your entire app
may live inside of a <Media>
or <Match>
component, and you calling
createElement
every render of your entire app that isn't actually
rendered would cause performance issues.
So, if you conditionally render content, consider using a render callback.
I'm very late to the conversation; however @ryanflorence's callback approach appears to yield a more ergonomic developer experience with regard to code correctness. I also think @gartz's re-render argument holds a lot of water. To demonstrate my argument, consider the following:
With the original approach, this code block will work as expected for the most part, but say
stuff
becomesnull
all of a sudden, what happens then? Your program will error out (cannot access key of undefined) because the children of<If>
are its function arguments and all function arguments are evaluated when passed in. Devs may therefore end up in a situation where their code fails unexpectedly. On the other hand, because the result of callbacks are not evaluated when passed into functions as arguments, implementing<If>
using the second approach is much safer.Something like the above should not crash your program arbitrarily, and holds the expectation that devs have: that the children of the
<If>
block are only evaluated whencond
is true. I'd love to hear what y'all think though ¨̮