Search code examples
reactjsreact-props

React.cloneElement vs render props pattern


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.


Solution

  • 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)
       }
    }