Search code examples
javascriptreactjsreact-reduxweb-component

Are react stateless components equal to ReacDOM.PureComponents


As per documentation(https://reactjs.org/docs/react-api.html#react.purecomponent)

"React.PureComponent is exactly like React.Component but implements shouldComponentUpdate() with a shallow prop and state comparison."

So if I define something like following,

const MyView = () => {
  return (
    <div>Hello Stateless Component</div>
  )
};

is it a React.PureComponent? Does it do a shallow prop and state comparison?


Solution

  • They are not equal at all.

    Stateless component or the official name React Stateless Functional Component(RSFC) has no "state".

    React components receive props for passing arguments from outside and use state object as inside state control object, we call setState function to modify state object to trigger rerender of the component, RSFC only receive props and return corresponding JSX elements, it has no "inside state" object.

    PureComponent is React.PureComopnent, it's not a generic term for a class of components, it's the React.PureComponent class which can be extended from, and we use

    class MyComponent extends React.PureComponent{}
    

    tell react that MyComponent is a pure component.

    if you want a <Clock/> component show and update time itself, you should use PureComponent and there no way to control time update in RSFC

    more info about differences between Component and PureComponent this article may be the help.