- Components are the building blocks of React. These are basically functions that return JSX markup.
Functional Components
- Functional components are simple JavaScript functions that return JSX markup / React Elements.
Props
are passed as an argument
- Before hooks, functional components were stateless, and could not hold or manage states, hooks make them fully capable of handling logic.
- Hooks are used to handle the lifecycle phases.
- React re-renders the if the props or state changes, it compares the new output with the previous output to update only the necessary parts in the UI
Purity of Components
- Pure components makes react more performant and predictable.
- Purity means, a function should not modify any state, prop or variable that is declared outside the scope of the function.
- If something really needs to be changed in a function which is outside the scope of the function most probably it will be side-effect.
- Now side-effect can be handled in event-handlers, so side-effects in event-handlers don’t make functions impure as, it won’t be triggered in render.
- If there’s something like API data fetching required, then it needs to be done under the
useEffect
hook, which is fine and doesn’t make the function impure too.
Functional vs Class Components
- Syntax -
Functional components are simpler, class components written as ES6 classes with extends
React.Component
with arender()
method returning JSX.
-
State Management Functional Components are stateless, but react hooks (
useState
) allows to hold and manage state. Class Components state is managed usingthis.state
object and updates are done viathis.setState
-
Lifecycle methods F.C. don’t have traditional lifecycle methods and rely on hooks C.C. have dedicated lifecycle methods like
componentDidMount
,componentDidUpdate
,componentWillUnmount
. -
Handling Side Effects F.C. have
useEffect
hook and event handler functions to handle the side effects C.C. side effects are spread across the lifecycle methods -
this
keyword Usage F.C. there’s nothis
keyword, everything is accessed via props, state hooks, while in C.C.this
keyword is to refer to component methods or state. Method needs to be bound either manually or using class field syntax
-
Reusability and Composition Functional Components: Custom Hooks allow logic to be easily abstracted and reused across components, promoting reusability and composition of logic. Class Components: To reuse logic in class components, higher-order components (HOCs) or render props patterns were used, which often resulted in wrapper hell and made code harder to maintain.
-
Error Boundaries New versions of react now have error boundaries concept, which is more flexible. Class components had error boundaries using methods to catch JavaScript errors in child components.