Hasty Briefsbeta

Bilingual

How Are Function Components Different from Classes? — overreacted

13 hours ago
  • Function components capture the props and state of a specific render via closures, preventing bugs from mutable `this` in class components.
  • Class components read from `this.props` or `this.state`, which are mutable and can lead to incorrect values in asynchronous callbacks like timeouts.
  • To fix class component bugs, developers often pass props explicitly or use closures inside `render`, but closures are naturally part of function components.
  • The same principle applies to Hooks: function components capture state at render time, ensuring correct behavior in async handlers.
  • For reading latest props or state, use `useRef` as an escape hatch, but it requires manual management and is not the default.
  • Stale closures in Hooks are often due to incorrect assumptions about value stability; closures themselves are a feature that improves correctness.
  • Performance differences between function and class components are negligible; the choice depends on the mental model and code clarity.