{"componentChunkName":"component---src-templates-post-js","path":"/react-class-component-guide/","result":{"data":{"markdownRemark":{"html":"<p>A <strong>React class component</strong> is one of the two primary ways to define a component in React. While functional components with Hooks have become the modern default, understanding the React class component is still essential for reading legacy codebases, migrating apps, and working with features like error boundaries. In this guide, I'll walk through what a React class component is, how it works, and compare <strong>React class vs functional component</strong> so you know which one to reach for.</p>\n<h2>What Is a React Class Component?</h2>\n<p>A React class component is a JavaScript ES6 class that extends <code>React.Component</code> and implements a <code>render()</code> method that returns JSX. Class components have access to local state via <code>this.state</code>, lifecycle methods like <code>componentDidMount</code>, and instance methods you can bind to event handlers.</p>\n<p>Here's the simplest possible React class component:</p>\n<pre><code class=\"language-jsx\">import React from \"react\";\n\nclass Welcome extends React.Component {\n  render() {\n    return &#x3C;h1>Hello, {this.props.name}&#x3C;/h1>;\n  }\n}\n\nexport default Welcome;\n</code></pre>\n<h2>React Class Component with State</h2>\n<p>State in a React class component lives on <code>this.state</code> and is updated with <code>this.setState()</code>. Never mutate <code>this.state</code> directly — always use <code>setState</code> so React knows to re-render.</p>\n<pre><code class=\"language-jsx\">import React from \"react\";\n\nclass Counter extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = { count: 0 };\n    this.increment = this.increment.bind(this);\n  }\n\n  increment() {\n    this.setState((prevState) => ({ count: prevState.count + 1 }));\n  }\n\n  render() {\n    return (\n      &#x3C;div>\n        &#x3C;p>Count: {this.state.count}&#x3C;/p>\n        &#x3C;button onClick={this.increment}>+1&#x3C;/button>\n      &#x3C;/div>\n    );\n  }\n}\n\nexport default Counter;\n</code></pre>\n<h2>Lifecycle Methods in a React Class Component</h2>\n<p>Lifecycle methods are one of the biggest reasons a React class component can still be useful. The most common ones are:</p>\n<ul>\n  <li><strong>componentDidMount()</strong> — runs once after the component mounts. Great for fetching data or setting up subscriptions.</li>\n  <li><strong>componentDidUpdate(prevProps, prevState)</strong> — runs after every update (but not the initial render).</li>\n  <li><strong>componentWillUnmount()</strong> — runs right before the component is removed. Use it to clean up timers, listeners, or subscriptions.</li>\n  <li><strong>shouldComponentUpdate(nextProps, nextState)</strong> — lets you skip re-renders for performance.</li>\n  <li><strong>getDerivedStateFromProps()</strong> and <strong>getSnapshotBeforeUpdate()</strong> — advanced, less common.</li>\n</ul>\n<pre><code class=\"language-jsx\">class UserProfile extends React.Component {\n  state = { user: null };\n\n  componentDidMount() {\n    fetch(`/api/users/${this.props.id}`)\n      .then((res) => res.json())\n      .then((user) => this.setState({ user }));\n  }\n\n  componentWillUnmount() {\n    // clean up here\n  }\n\n  render() {\n    const { user } = this.state;\n    if (!user) return &#x3C;p>Loading…&#x3C;/p>;\n    return &#x3C;h2>{user.name}&#x3C;/h2>;\n  }\n}\n</code></pre>\n<h2>React Class vs Functional Component</h2>\n<p>So when should you use a React class component vs a functional component? Here's a side-by-side breakdown of <strong>React class vs functional component</strong>:</p>\n<h3>Syntax</h3>\n<p>A functional component is just a function that returns JSX. A React class component is a class that extends <code>React.Component</code> and has a <code>render()</code> method. Functional components are shorter and easier to read.</p>\n<pre><code class=\"language-jsx\">// Functional component\nfunction Welcome({ name }) {\n  return &#x3C;h1>Hello, {name}&#x3C;/h1>;\n}\n\n// React class component\nclass Welcome extends React.Component {\n  render() {\n    return &#x3C;h1>Hello, {this.props.name}&#x3C;/h1>;\n  }\n}\n</code></pre>\n<h3>State</h3>\n<p>React class component uses <code>this.state</code> and <code>this.setState</code>. Functional components use the <code>useState</code> Hook. Hooks let you split state into multiple independent variables, which is often cleaner than one big state object.</p>\n<h3>Lifecycle</h3>\n<p>A React class component uses dedicated lifecycle methods. A functional component uses the <code>useEffect</code> Hook to cover mounting, updating, and unmounting — usually with less code.</p>\n<h3>Performance</h3>\n<p>Both approaches perform similarly in most real-world apps. Functional components can be optimized with <code>React.memo</code>, and class components with <code>shouldComponentUpdate</code> or <code>PureComponent</code>.</p>\n<h3>Readability and Reusability</h3>\n<p>Functional components with custom Hooks make it much easier to extract and reuse logic across components. In a React class component, the equivalent patterns (higher-order components, render props) tend to produce deeply nested \"wrapper hell.\"</p>\n<h3>`this` Binding</h3>\n<p>A React class component forces you to think about <code>this</code> — you typically bind event handlers in the constructor or use class field arrow functions. Functional components don't have a <code>this</code>, so this whole category of bugs simply goes away.</p>\n<h2>When Should You Still Use a React Class Component?</h2>\n<ul>\n  <li><strong>Error boundaries.</strong> As of today, error boundaries still require a class component because they rely on <code>componentDidCatch</code> and <code>getDerivedStateFromError</code>.</li>\n  <li><strong>Legacy codebases.</strong> If your team's code is mostly class components, consistency can be more valuable than mixing styles.</li>\n  <li><strong>Learning React's history.</strong> Understanding the React class component makes lifecycle-aware thinking click, which transfers directly to <code>useEffect</code>.</li>\n</ul>\n<h2>Converting a React Class Component to a Functional Component</h2>\n<p>Most React class components can be rewritten as functional components using Hooks. A quick cheat sheet:</p>\n<ul>\n  <li><code>this.state</code> + <code>this.setState</code> → <code>useState</code></li>\n  <li><code>componentDidMount</code> → <code>useEffect(fn, [])</code></li>\n  <li><code>componentDidUpdate</code> → <code>useEffect(fn, [deps])</code></li>\n  <li><code>componentWillUnmount</code> → the cleanup function returned from <code>useEffect</code></li>\n  <li><code>this.context</code> → <code>useContext</code></li>\n  <li>Instance variables → <code>useRef</code></li>\n</ul>\n<pre><code class=\"language-jsx\">// Before: React class component\nclass Counter extends React.Component {\n  state = { count: 0 };\n  componentDidMount() {\n    document.title = `Count: ${this.state.count}`;\n  }\n  componentDidUpdate() {\n    document.title = `Count: ${this.state.count}`;\n  }\n  render() {\n    return (\n      &#x3C;button onClick={() => this.setState({ count: this.state.count + 1 })}>\n        {this.state.count}\n      &#x3C;/button>\n    );\n  }\n}\n\n// After: functional component with Hooks\nfunction Counter() {\n  const [count, setCount] = React.useState(0);\n  React.useEffect(() => {\n    document.title = `Count: ${count}`;\n  }, [count]);\n  return &#x3C;button onClick={() => setCount(count + 1)}>{count}&#x3C;/button>;\n}\n</code></pre>\n<h2>React Class Component FAQ</h2>\n<h3>Is the React class component deprecated?</h3>\n<p>No. The React team has repeatedly said they have no plans to remove class components. They are still fully supported in the latest versions of React. That said, new features and most documentation are focused on Hooks and functional components.</p>\n<h3>Can a React class component use Hooks?</h3>\n<p>No — Hooks can only be called inside functional components or other custom Hooks. If you need Hook-style logic inside a class, you'll need to wrap it with a small functional component or refactor.</p>\n<h3>React class vs functional component: which is faster?</h3>\n<p>For almost every app, the difference is negligible. Focus on correctness, readability, and reusability first. Profile only if you have a measured performance problem.</p>\n<h2>Conclusion</h2>\n<p>The React class component isn't going anywhere, but functional components with Hooks are the modern default. Use a class component when you need an error boundary or are working in a class-heavy codebase, and reach for functional components everywhere else. Once you've internalized the React class vs functional component trade-offs, you can pick the right tool for each job with confidence.</p>\n<p>If you found this React class component guide helpful, feel free to reach out on LinkedIn — I'd love to hear what you're building.</p>","frontmatter":{"title":"React Class Component: A Complete Guide (and React Class vs Functional Component)","date":"04/19/2025","excerpt":"Everything you need to know about the React class component — syntax, lifecycle methods, state, and when to choose a React class component vs a functional component in modern React."}}},"pageContext":{"slug":"/react-class-component-guide/"}},"staticQueryHashes":["3943644438"]}