Pure React Component VS Functional React Component with a simple demo

Have you ever wondered, that if both functional stateless component and pure react components are supposed to be used in cases when your component renders same markup for same set of props, what is the use case for each for them? Are they interchangeable? Not really! This post will explain that with a simple example.

Suppose you want to create a simple app where we show a random quote from a list of quotes. The quote component will be a child of another stateful component.

Implementation using functional stateless component

Can you identify the bug in the above code? If you run it you will see that as soon as the component is rendered it displays a random quote, but after username state changes, it displays another random quote! A functional stateless component will re render every time the state ofthe parent component changes. Due to the limitations of a functional component you cannot implement life cycle hooks like shouldComponentUpdateto make explicit checks for renders.

Pure component solves this issue. Pure Component implementsshouldComponentUpdate for you out of the box. Lets have a look at the same example with Pure component.

Implementation using Pure Component

If you run the above code, you will notice that even though the state of the parent changes, the quote displayed, doesn’t change. Pure component also gives a more stable UI because it will only re render when a prop on which it depends will change.It is recommended by React team that you use PureComponent instead of manually implementing shouldComponentUpdate, because PureComponent performs a shallow comparison of props and state, and reduces the chance that you’ll skip a necessary update.