DEV Community

Dan Zhang
Dan Zhang

Posted on

1

What was wrong with class components?

There is something beautiful and pure about the notion of a stateless component that takes some props and returns a React element. It is a pure function and as such, side effect free.

export const Heading: React.FC = ({ level, className, tabIndex, children, ...rest }) => {
const Tag = h${level} as Taggable;

return (

{children}

);
};

Unfortunately, the lack of side effects makes these stateless components a bit limited, and in the end, something somewhere must manipulate state. In React, this generally meant that side effects are added to stateful class components. These class components, often called container components, execute the side effects and pass props down to these pure stateless component functions.

There are several well-documented problems with the class-based lifecycle events. One of the biggest complaints is that you often have to repeat logic in componentDidMount and componentDidUpdate.

async componentDidMount() {
const response = await get(/users);
this.setState({ users: response.data });
};

async componentDidUpdate(prevProps) {
if (prevProps.resource !== this.props.resource) {
const response = await get(/users);
this.setState({ users: response.data });
}
};
If you have used React for any length of time, you will have encountered this problem.

With Hooks, this side effect code can be handled in one place using the effect Hook.

const UsersContainer: React.FC = () => {
const [ users, setUsers ] = useState([]);
const [ showDetails, setShowDetails ] = useState(false);

const fetchUsers = async () => {
const response = await get('/users');
setUsers(response.data);
};

useEffect( () => {
fetchUsers(users)
}, [ users ]
);

// etc.
The useEffect Hook is a considerable improvement, but this is a big step away from the pure stateless functions we previously had. Which brings me to my first frustration.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay