wh1t3cat1k
wh1t3cat1k

Reputation: 3186

Pass component instance directly into prop or use a render callback?

What would be the idiomatic and/or more effective way of handling a situation whereby the parent component wants the child to render some custom JSX?

Example:

// Option 1
// -
const rightChild = <View />

<NavigationBar rightChild={rightChild} />

// Option 2
// -
const renderRightChild = () => <View />

<NavigationBar renderRightChild={rightChild}>

(lambdas are used for simplicity, I am aware of the performance implications)

Upvotes: 1

Views: 1008

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074158

This:

const rightChild = <View />
// ...
<NavigationBar rightChild={rightChild} />

...isn't "passing JSX into the prop." It's passing a React element. The JSX is processed by const rightChild = <View /> (turned into React.createElement call) and the result (a React element) is stored in rightChild. That's normal, though it's usually as a child (ending up on the children prop) rather than a separate named prop. But either way, it's a prop, so...

As far as I know, that would be the standard way to do it. You could also just put the JSX in the property

<NavigationBar rightChild={<View />} />

(Side note: Executing <View /> creates a new React element each time, just like it would if <View /> were a child instead: <Something><View/></Something>]. Your const rightChild = <View />; is probably recreating it every time as well, depending on where that line of code is. That's quite normal. But if <View /> never changes, you could create it once and reuse it, which would avoid rerendering it when the parent renders. Or you could use useMemo [or React.memo for class components]. There are trade-offs involved in memoization, see Should you add memo everywhere? in the React documentation.)

Upvotes: 3

Keith Rousseau
Keith Rousseau

Reputation: 4475

Either way will work. The case for when you really want to use a render prop is when you will need the props passed from NavigationBar in order to render the component or fragment. The benefit to passing in a component is that you will not be passing in a new function to be rendered each time. From a performance standpoint it would be a bit easier to get it to not for a re-render.

Upvotes: 1

Related Questions