REACT Components

What are react components?

  • React is divided into small building blocks called components. These small components make designing the webpage easier.

  • There are two types Of Component

    • Class-Based Component

    • Functional Component (Introduced in REACT-18)

Functional Component

  1. These are basically JavaScript functions that return a JSX.

  2. Important Properties Of Functional Components

    • As a matter of convention, we write the component name in capital letters

    • A function that returns JSX might not be a component, depending on how it is used.

    • To be a component function returning JSX should be used as <Component /> and not as Component().

    • When a functional component is used as <Component /> it will have a lifecycle and can have a state.

    • When a function is called directly as Component() it will just run and (probably) return something. No lifecycle, no hooks, none of the React magic. It's very similar to assigning some JSX to a variable, but with more flexibility (you can use if statements, switch, throw, etc.).

    • Using state in a non-component is dangerous.

    • Using functions that return JSX without being a component might be officially considered to be an anti-pattern in the future. There are edge cases (like render props), but generally, you almost always want to refactor those functions to be components because it's the recommended way.

    • If you have to declare a function that returns JSX inside a functional component (for instance, due to tightly coupled logic), directly calling it as {component()} could be a better choice than using it as <Component />.

    • Converting simple <Component /> into {Component()} might be very handy for debugging purposes.

Examples :

React-components-blog-image.jpg

What is the advantage of using REACT components

  • The advantage of using react components we can reuse these components.

  • Testing and debugging become easier since instead of having a single large file we have a file divided into small different components.

React-components-blog-image.jpg