Noitidart
Noitidart

Reputation: 37238

Good practice to pass function in props?

I know that React does diffing of the this.state. But when you are in a child component, diff is done on this.props. So I was wondering how does the diffing system diff if the value of a prop is a function? Is it bad practice, (as in bad for perf or something), if I put a function into the this.props or this.state?

Upvotes: 2

Views: 1365

Answers (2)

Sagi Medina
Sagi Medina

Reputation: 915

Pass the unbound function to the child component, and have the child use an instance method, e.g:

class Container extends Component {

    deleteItem(index) {
        actionThatDeletesSomething(index);
    }

    render(){
        return(
            <ChildComponent deleteItem={ this.deleteItem } />
        )
    }
}


class ChildComponent extends Component {

    render(){
        return(
            <a onClick={ this.props.deleteItem(index) } />
        )
    }
}

Upvotes: -1

Oleksandr T.
Oleksandr T.

Reputation: 77482

If you pass to child component function as a props diff algorithm will be constantly triggered. If you care about this case you can implement shouldComponentUpdate where you can ignore properties which contains functions.

You can experiment with this example

Upvotes: 2

Related Questions