I'm learning React and trying to figure out the best way to dynamically add props. I know two approaches how to do that, but cannot understand which one is better and faster.
First way is to use React.cloneElement api
const Parent = ({ children }) => {
const child = React.cloneElement(children, { newProp: 'some new prop' });
return child;
};
const Child = ({ newProp }) => <div>{newProp}</div>;
const App = () => (
<Parent>
<Child />
</Parent>
);
The second way is to use "render props" pattern, described on official React site: Render Props
const Parent = ({ render }) => {
const newProp = 'some new prop';
return render(newProp);
}
const Child = ({ newProp }) => <div>{newProp}</div>;
const App = () => (
<Parent render={props => <Child newProp={props} />} />
);
Both approaches give same results, but I don't know what is going on under the hood and which way to use.
React. cloneElement() is useful when you want to add or modify the props of a parent component's children while avoiding unnecessary duplicate code.
For the most part, HOC and render prop components solve the same problem. However, render prop components provide are gaining popularity because they are more declarative and flexible than an HOC. Read more: Use a render prop.
The term “render prop” refers to a technique for sharing code between React components using a prop whose value is a function. In simple words, render props are simply props of a component where you can pass functions. These functions need to return elements, which will be used in rendering the components.
createElement is the code that JSX gets compiled or converted into and is used by reacting to create elements. cloneElement is used for cloning elements and passing them new props.
React.cloneElement
is a helper that's usually used to pass inline-props
to avoid polluted codes. Instead of passing a prop down like this:
return <Child propA={myProps.propA} propB={myProps.propB} />
You can do this:
return React.cloneElement(Child, {...myProps})
Which is almost the same as:
return <Child {...myProps} />
The only difference here is that cloneElement
will preserve previously attached refs
.
Now renderProps
is a technique to reuse stateful logic
and has different applications than cloneElement
. The first will help you with props
manipulation, the second is an equivalent to High Order Components
and is used whenever you want to reuse some logic to dinamically inject props into your children:
class Animation extends Component{
state = {}
componentDidMount(){/*...*/}
componentDidUpdate(){/*...*/}
render(){
const { customProps } = this.state
const { children } = this.props
return children(customProps)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With