Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking prop types in React

I was reading the React.Component section in the official React documentation. Everything made sense except for the part regarding propTypes. The docs state the following:

In production mode, propTypes checks are skipped for efficiency.

Say I have the following code:

class Sample extends React.Component {
    render() {
        return (
            <div>Hello {this.props.name}</div>
        );
    }
}

Sample.propTypes = {
    name: React.PropTypes.string
};

Does the docs imply that in production my type checks against props will be skipped? If yes, how should I be checking prop types?

like image 455
Amous Avatar asked Mar 10 '23 11:03

Amous


1 Answers

You don't check against the prop types yourself at all, React does that for you.

However, as the docs say, only as long as you are in development mode. Every prop type check is essentially a function call that uses processing power and memory.


While you are in development, knowing that one of your props has the wrong type makes this cost a worthy trade-off.

Once you are in production, your app should be tested thoroughly enough already that none of your prop type validations fail anymore anyway.

For this reason, they are skipped to make your app a bit more efficient instead.

like image 131
TimoStaudinger Avatar answered Mar 20 '23 19:03

TimoStaudinger