DEV Community

Dan Zhang
Dan Zhang

Posted on

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.

Top comments (0)