Robert Taussig
Robert Taussig

Reputation: 581

React and Redux: Are there any performance issues/possible side effects with passing a parent component as a prop to its children

I'm reviewing some code in a React-Redux codebase, and there are quite a few cases where a parent smart component is being passed as a prop to a child component:

import React from 'react';
import Child from '../components/Child';

export default class Parent extends React.Component {
    constructor(props) {
        super(props);
    }
    //...

    render() {
        return <Child parent={this}/>;
    }
}

At initial glance, it appears that the intention here is to expose the props/state/methods of the parent to the child component. This sort of goes against many of the design patterns I've used in the past with React, but I'm not sure if it's something that is worth bringing up in a code review (it's already deployed to QA). It technically works (the child is able to call this.props.parent[method], etc) and significantly reduces the lines of code otherwise required if you pass individual handlers/slices of props/(local)state to the child. I know there are downsides (in one case, the parent property shared the same name as a reducer, so in the child component, it is unclear if this.props['reducerName'] is referring to a React Component or a mapped slice of state), but I can't be sure that the downsides are anything more than surface level.

Does something like this run the risk of unnecessary rerenders/diff checks in the child component? Does React ever need to recursively serialize components, and thus incur a lot of overhead because of circular references? Anything I can point out besides I don't think it looks right?

Upvotes: 2

Views: 65

Answers (1)

sudheer singh
sudheer singh

Reputation: 922

There are a few things I can think of why this might not be a good Idea:

  • This creates a very tight coupling between the parent and the component. Further, we should try to provide the minimum amount of data to the abstract modules. We call it Principle of least privilege. Here, a lot of information is being passed to the child component which will not be used and can even be abused using a lot of ways.
  • One case where it can be very bad idea is when the child component changes something on the date object: eg :

    render() {
        return (
          <React.Fragment>
            <ChildOne parent={this}/>;
            <ChildTwo parent={this}/>;
          </React.Fragment>
       )
    }
    

    Now the ChildOne component can do something like :

this.props.parent.clickHandler = this.anotherHandler

This will break ChildTwo functionality.

Upvotes: 3

Related Questions