Ben Aston
Ben Aston

Reputation: 55729

Is ReactJS "clever" when it comes to invoking the render method?

The render method of this component does use any of the props supplied to the component.

Will the component re-render when the props change regardless?

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    const { propValue } = props;
    // do something with propValue...
  }
  render () {
    return (
      <div>foo</div>
    );
  }
}

Upvotes: 4

Views: 63

Answers (3)

Roopak Puthenveettil
Roopak Puthenveettil

Reputation: 1475

As far as i know react will call the render method in the following scenarios

  1. when your component get mounted initially
  2. when state got changed using this.setState()
  3. when your component receives new props
  4. when this.forceUpdate() get called.

since you didn't implement shouldcomponentUpdate() the render method is going to get called

Upvotes: 0

Marko
Marko

Reputation: 5552

Yes, the component will re-render unless you implement shouldComponentUpdate. You can inherit from PureComponent which uses shallow comparison of prop and state with previous values to determine if component should update or not.

Upvotes: 3

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

Will render be called - yes. Unless you implement shouldComponentUpdate to return false.

Will the DOM be rerendered - no.

Also you might want to take a look at https://babeljs.io/docs/plugins/transform-react-constant-elements/ that hoists static elements up.

In

const Hr = () => {
  return <hr className="hr" />;
};

Out

const _ref = <hr className="hr" />;

const Hr = () => {
  return _ref;
};

Upvotes: 3

Related Questions