Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - passing 'this' as a prop

Is there any side effect I do not see by doing this ?

class App extends React.Component {
    hello() {
        console.log("hello")
    }

    render() {
        return <Layout app={this}>
    }
}

So later on I can refer to this.props.app.hello (and others) from Layout ?

like image 428
Yomain Avatar asked Oct 28 '25 02:10

Yomain


1 Answers

This is not safe.

React will not know how to watch for changes, so you may miss re-renders. React uses === to check for state changes, and App will always be === to App, even when state or properties change.

Take this example:

class App extends React.Component {
    constructor(props) {
        super(props);
        this.setState({text: 'default value'});
    }

    hello() {
        this.setState({...this.state, text: 'new value'});
    }

    render() {
        return (
            <div onClick={this.hello}>
                <Layout app={this}>
            </div>
        );
    }
}

class Layout extends React.Component {
    render() {
        return <div>{this.app.state.text}</div>
    }
}

When you click on the parent div, this.hello will be called, but the child component will not detect the state update, and may not re-render as expected. If it does re-render, it will be because the parent did. Relying on this will cause future bugs.

A safer pattern is to pass only what is needed into props:

class App extends React.Component {
    //...

    render() {
        return (
            <div onClick={this.hello}>
                <Layout text={this.state.text}>
            </div>
        );
    }
}

class Layout extends React.Component {
    render() {
        return <div>{this.props.text}</div>
    }
}

This will update as expected.

like image 76
Joshua Wade Avatar answered Oct 30 '25 17:10

Joshua Wade



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!