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.
@ryanflorence you should follow your own advice and take time to read source code or at least create tests to prove your theories, you are still wrong, I will tell you why.
There is a good reason why
React.createElement
is called multiple times and it really doesn't make much difference, go ahead and read the source code from it, you might learn something or prove that I'm wrong and teach me something.What you're recommending here is a micro-optimization that hurts the syntax for no real performance gains, extending object properties is a very cheap operation and the heavy operations are in the Constructor and Render of components, what I've already proved your solution doesn't change it.