شبكة تعلم مع ناو

ما الفرق بين Function Components وClass Components في React؟

  • Function Components: دوال عادية. منذ ظهور Hooks تستطيع استخدام الحالة والتأثيرات (useState وuseEffect). هي الطريقة الموصى بها اليوم.
  • Class Components: كلاسات تستخدم this.state ودوال دورة الحياة مثل componentDidMount، ولا تستطيع استخدام Hooks.
// function component
function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}

// class component
class Counter extends React.Component {
  state = { count: 0 };
  render() {
    return (
      <button onClick={() => this.setState({ count: this.state.count + 1 })}>
        {this.state.count}
      </button>
    );
  }
}

ستجد مكونات الكلاس في المشاريع القديمة، لكن المشاريع الجديدة تستخدم الدوال.

اختبر نفسك

خمسة أسئلة سريعة، مع الإجابة والشرح بعد كل سؤال.