DEV Community

Daniel Joo
Daniel Joo

Posted on

Class vs Pure vs Functional Components in React

When first learning React and looking through source code on the Internet, I found myself slightly confused by the different types of components. Although one could go about only using class components throughout his or her application, pure and functional components can come in handy and allow for more clarity/organization within an application. Let's get into the differences between the three components.

Class components

Class components are the go-to components in React. They can be used exclusively throughout an entire application, and are the components that are most frequently used. Here is an example of a very simple class component.

   import React from 'react'

   class App extends React.Component {
     render() {
      return <div></div>
      }
   }

   export default App

Pure components

So what exactly are pure components? As the name suggests, the concept of a pure component is very similar to that of a pure function. In a pure function, if you put in the same input "x" number of times, you will get the same output "x" number of times. Putting in the same input will always lead to the same output in a pure function. Similarily, if a pure component is given the same state and props, it will always behave in the same way. A pure component does not have access to shouldComponentUpdate. What this means is that there is an automatic, shallow comparison of old and new props and state. Pure components are written pretty much the same way as class components with a minor tweak.

   import React, { PureComponent } from 'react'

   class App extends PureComponent {
     render() {
       return <div></div>
     }
   }

   export default App

Functional components

Functional components come in handy when you know that you don't need to include state or lifecycle methods in your component. Class components automatically check for lifecycle methods, and if you don't need to utilize them, you can simply use functional components. Because there are no lifecycle methods, render is not used. Functional components are a good option when all you want do is display something in your component and not include logic. They can take in props from parent components and re-render based on changes in props in the parent components. Functional components can also re-render if their parent components re-render. A functional component returns JSX and can be written like this:

   import React from 'react'

   const App = props => {
     return (
       <div>{props.message}</div>
     )
   }

   export default App

Top comments (1)

Collapse
 
mohanbvej profile image
mohanbvej

ok good but , where can we assing state ?? in class component or in pure component ?? plz clarify