React Components: Class vs Functional - Why Modern React Prefers Functions ??

React Components: Class vs Functional - Why Modern React Prefers Functions ??

Remember when React components were all about classes? Fast forward to 2024, and functional components have become the standard. Let's dive into this evolution and understand why the shift happened!

The Evolution Journey ??

Class Components (The Past)

jsx

class Welcome extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  handleClick = () => {
    this.setState({ count: this.state.count + 1 });
  }

  render() {
    return (
      <div>
        <h1>Hello, {this.props.name}</h1>
        <button onClick={this.handleClick}>
          Clicked {this.state.count} times
        </button>
      </div>
    );
  }
}        

Functional Components (The Present)

jsx

function Welcome({ name }) {
  const [count, setCount] = useState(0);

  return (
    <div>
      <h1>Hello, {name}</h1>
      <button onClick={() => setCount(count + 1)}>
        Clicked {count} times
      </button>
    </div>
  );
}        

Why Functional Components Win ??

1. Simplicity

  • Less boilerplate code
  • No need for constructor
  • No binding of methods
  • No use of 'this' keyword

2. Hooks Power

jsx

function UserProfile({ userId }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchUser(userId)
      .then(data => {
        setUser(data);
        setLoading(false);
      });
  }, [userId]);

  if (loading) return <Loader />;
  return <Profile user={user} />;
}        

3. Better Performance

  • Smaller bundle size
  • No overhead from class instances
  • Better tree-shaking support
  • Easier code splitting

4. Reusability Through Custom Hooks

// Custom Hook
function useWindowSize() {
  const [size, setSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight
  });

  useEffect(() => {
    const handleResize = () => {
      setSize({
        width: window.innerWidth,
        height: window.innerHeight
      });
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return size;
}

// Using the custom hook
function ResponsiveComponent() {
  const { width, height } = useWindowSize();
  return <div>Window size: {width} x {height}</div>;
}        

When to Still Use Class Components? ??

  1. Legacy codebase maintenance
  2. Error Boundaries (still requires classes)
  3. When working with older React versions

The Future is Functional ??

jsx

// Modern React Pattern
function Counter() {
  const [count, setCount] = useState(0);
  const increment = useCallback(() => setCount(c => c + 1), []);
  
  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);

  return (
    <button onClick={increment}>
      Count: {count}
    </button>
  );
}        

?? Weekly Challenge

jsx

class Timer extends React.Component {
  state = { seconds: 0 };
  
  componentDidMount() {
    this.interval = setInterval(() => {
      this.setState(state => ({
        seconds: state.seconds + 1
      }));
    }, 1000);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  render() {
    return <div>Seconds: {this.state.seconds}</div>;
  }
}        

Share your solution in the comments!

#React #WebDevelopment #JavaScript #Programming #FrontEnd #ReactHooks #LinkedInLearning


Dhruv Patel

"MEAN Stack Developer | Full-Stack Web Applications | Specialist in E-commerce, HRMS & Real-time Systems"

2 个月

Very helpful

回复

要查看或添加评论,请登录

Dhruv Patel的更多文章

社区洞察

其他会员也浏览了