DEV Community

nedajahanfar
nedajahanfar

Posted on

When to use a Class Component? When to use a Function Component?

Before React 16.8, class components were recommended because they had lifecycle methods (special functions that let you run code during the different phases of a component's life).
But after React 16.8, with the introduction of hooks, functional components can now do the same things — so they became the new best practice.

Before React 16.8, if you wanted to:

Run some code when a component mounted

React to state or prop changes

Clean things up when a component unmounted

=> You needed to use class components because they had lifecycle methods like:

componentDidMount

componentDidUpdate

componentWillUnmount

React 16.8 introduced Hooks — especially:

useState() for state

useEffect() for lifecycle behavior

This made it possible to do everything class components could do, but in a simpler, cleaner way inside functional components.

Most companies now use functional components with hooks.
But class components still exist in older codebases, so it's smart to be familiar with both.

Top comments (0)