Class Component in React
Table Of Contents
· Return vs Render()
· State Management
· Lifecycle
· Context
· Error Boundaries
Return vs Render()
Class Component
class Users extends Component {
render() {
return (
<div>
<button onClick={this.toggleUsersHandler.bind(this)}>
{this.state.showUsers ? ‘Hide’ : ‘Show’} Users
</button>
{this.state.showUsers && usersList}
</div>
);
}
}Function Component
const Users = () => {
return ( // directly returns without using render()
<div className={classes.users}>
<button onClick={toggleUsersHandler}>
{showUsers ? ‘Hide’ : ‘Show’} Users
</button>
{showUsers && usersList}
</div>
);
};
Key Differences
- Class Component must use render() method
- Function Component directly return JSX
- Class component need ‘this’ to access props and state (‘this’ refers to the current context)
State Management
Class Component
class Users extends Component {
constructor() {
super();
this.state = {
showUsers: true
}
}
toggleUsersHandler() {
this.setState((curState) => {
return { showUsers: !curState.showUsers }
});
}
}Function Component
const Users = () => {
const [showUsers, setShowUsers] = useState(true);
const toggleUsersHandler = () => {
setShowUsers((curState) => !curState);
};
}
Key Differences
- Class : State is an object in constructor
- Function : use ‘useState’ hook and Value can be anything
Lifecycle
Lifecycle Method Equivalents as follows (Class to Function)
- componentDidMount -> useEffect(() => {},[])
- componentDidUpdate -> useEffect(() => {},[dependencies])
- componentWillUnmount -> useEffect(() => {return () => {}} , [])
Key Differences
- Class component have explicit lifecycle methods
- Function components use ‘useEffect’ for all lifecycle operations
- Function components are more flexible with dependencies
Context
Create Context ( same for both )
Get bytePudding’s stories in your inbox
Join Medium for free to get updates from this writer.
user-context.js (usually in a seperate file)
const userContext = React.createContext({users : [] });
export default userContextProvider (same for both)
const userContext = {users : DUMMY_USERS};
return (
<UserContext.Provider value={userContext}>
<UserFinder />
<UserContext.Provider>
)context will be used in components as follows
In a Class Component
class UserFinder extends Component {
//1. Using static contextType
static contextType = UsersContext;
componentDidMount() {
// 2. Access via this.context
this.setState({ filteredUsers: this.context.users });
}
}
In a Function Component
const UserFinder = () => {
// 1.Using useContext hook
const usersContext = useContext(UsersContext);
const [filteredUsers, setFilteredUsers] = useState([]);
useEffect(() => {
// 2.Access directly
setFilteredUsers(usersContext.users);
}, []);
};
Error Boundaries
Error Boundaries are React Component that catch JavaScript errors anywhere in their child component tree. They work like a JavaScript catch{} block , but for components
Implementation
class ErrorBoundary extends Component {
constructor(){
super();
// initialize state with hasError set to false
this.state = { hasError : false }
}
// componentDidCatch is a lifecycle method that runs when an error occurs
componentDidCatch(error){
this.setState({hasError: true});
}
render(){
// if there's an error, show the error UI
if(this.state.hasError){
return <p> something went wrong </p>
}
// if no error , render the children component normally
return this.props.children
}
}
export default ErrorBoundaryHow it’s used
<ErrorBoundary>
<Users users={this.state.filteredUsers} />
</ErrorBoundary>- when there’s error in Users componenet, ErrorBoundary component will catch the error (componentDidCatch) and renders the customed error ui
What Errors It Catches
Errors in render phase
class UserComponent extends Component {
render() {
const user = undefined;
// Cannot read property 'name' of undefined
// this will be caught by error boundary
return <div>{user.name}</div>;
}
}Errors in constructors of child components
class UserComponent extends Component {
constructor() {
super();
// this will be caught by error boundary
throw new Error('Constructor Error');
}
}Error Boundary Does NOT catch errors in : Event Handlers , Async Code Errors, Promise rejections , Server side rendering , errors within itself
// 1. Event Handler Errors
const UserComponent = () => {
const handleClick = () => {
// this error will NOT be caught by Error Boundary
throw new Error('event handler error');
};
return <button onClick={handleClick}>Click</button>;
};
// 2. Async Code Errors
const UserComponent = () => {
useEffect(() => {
// this error will NOT be caught by Error Boundary
setTimeout(() => {
throw new Error('Async Error');
}, 1000);
}, []);
return <div>Async Component</div>;
};
// 3. Promise rejection
const UserComponent = () => {
useEffect(() => {
// this error will NOT be caught by Error Boundary
Promise.reject(new Error('Promise Error'));
}, []);
return <div>Promise Component</div>;
};
// 4. Server side rendering errors
// Errors occured during SSR will not be caught in client-sideClass Component Exception
If you’re using only function components, you’ll need to create a class component for the Error Boundary. This is one of the few cases where class components are still necessary in modern React. The React team has mentioned they’re working on a hook-based solution for Error Boundaries, but it’s not available yet ( 2025 )








