React Components

React Components

DOM, React Element/Component, Functional/ Class, Stateless/Stateful, Pure, HOC components

Table of contents

No heading

No headings in the article.

You've ever experienced that bad feeling of not remembering the simple things about an ecosystem you mastered while learning that craft? I know the feeling. That's the sole reason I'm writing this overview of React components(Functional, Class, HOC, Pure, Stateless, Stateful , { pure } HOC from Recompose). This can be anyone's reference whether a novice or a master in React.

What is a DOM(Document Object Model)

Is an application programming interface (API) for HTML and XML documents

What is a Virtual DOM

Is a representation of a user interface that is kept in memory and in sync with the real DOM

What is a Shadow DOM (A web concept, not a React concept) It allows hidden DOM trees to be attached to elements in the regular DOM tree

What is a React Element

Describes what you want to see on the screen(object representation of a DOM node)

To create a React element (object representation of a DOM node), we use React's createElement method.

It takes in 3 arguments:

  1. tag name e.g (div, span, h1,..etc)
  2. attributes e.g (id, class)
  3. children (contents of the element) in the case below, the text "Login
const element = React.createElement(
  'div',
 {id:  'login-btn'},
'Login'
)

After invoking the createElement fn it returns the an object that looks like below

{
  type: 'div',
  props: {
    children: 'Login',
    id: 'login-btn'
  }
}

When it’s rendered to the DOM using render() method from react-dom

import { render } from 'react-dom';
render(element, document.getElementById('root'));

we’ll have a new DOM node that looks like this,


<div id='login-btn'>Login</div>

What is a React Component

A React Component is Javascript function that return JSX/HTML. Usually independent and reusable.

Types React Components

  1. Functional components
  2. Class components

Functional Vs Class Components

A Functional component is a plain Javascript function that returns JSX(Javascript XML). (It accepts a single props object and returns a React element).

A Class component is a Javascript class that extends React.Component and returns JSX inside a render method.

//  functional component - returns Header component
function Header(props) {
  return (
      <h1> React  Version { props.version || 18 } </h1>
    )
}
//  class component - returns Header component
class Header extends React.Component {
render() {
    return (
        <h1> React  Version { this.props.version || 18 } </h1>
      )
   }
}

Stateless vs Stateful components

Stateless components are components that have no state, no lifecycle hooks.

Stateful components are components that hold some state

What is a pure function?

In functional programming paradigm, a function is said to be pure if it meets the following two conditions:

  1. Its return value is only determined by its input values.
  2. Its return value is always the same as the input values.

What is a pure component in React?

Is a component that renders the same output for the same state and props.

Components that extends React.PureComponent class are treated as pure components.

  • Pure components have some performance improvements and render optimization since React implements the shouldComponentUpdate() method for them with a shallow comparison for props and state
//  pure component - class based
class SquaredNumber extends React.PureComponent {
render() {
const { label = "Squared", n = 5 } = this.props
    return (
       <div>
            <h6>{ label }</h6>
            <span>{ n * n }</span>
        </div>
      )
   }
}

Functional components cannot leverage the performance improvements and render optimizations that come with React.PureComponent since by definition, they are not classes

However, we can use either {pure} HOC from Recompose or React.memo() to create memoized functional components.

Using {pure} HOC from Recompose

This makes React treat a functional component as pure, so we don't have to convert the component to a class component.

//  pure HOC from Recompose 
import { pure } from 'recompose';

function SquaredNumber({ label = "Squared", n = 5 }) {
  return (
    <div>
        <h6>{ label }</h6>
        <span>{ n*n }</span>
    </div>
  )
}
// Wrap component using the `pure` HOC from recompose
export default pure(SquaredNumber);

Using React.memo()

React.memo() create a memoized functional components, they prevent rendering on unncessary updates using shallow comparison of props.

//  using React.memo() HOC
import { memo } from 'react';

function SquaredNumber({ label = "Squared", n = 5 }) {
  return (
    <div>
        <h6>{ label }</h6>
        <span>{ n*n }</span>
    </div>
  )
}
// Wrap component using React.memo()
export default memo(SquaredNumber);

React.memo() is a HOC, it takes React component as its first argument and returns a React component that renders while memoizing the output.

If the component's props are shallowly equal, React.memo() component will bail out the updates. React.memo() also takes in a second argument arePropsEqual() function, this returns true when props to be compared are equal otherwise false when not equal.

The arePropsEqual() function acts very similar to the shouldComponentUpdate() lifecycle method in class components.

//  using React.memo() HOC with arePropsEqual second arg
import { memo } from 'react';

function SquaredNumber({ label = "Squared", n = 5 }) {
  return (
    <div>
        <h6>{ label }</h6>
        <span>{ n*n }</span>
    </div>
  )
}
// Wrap component using `React.memo()` and pass `arePropsEqual`
export default memo(SquaredNumber, arePropsEqual);

Few questions asked on components

  1. A React Component

    A React Components are Javascript functions that return JSX/HTML, are the building blocks of a React Application

  2. What is a HOC component?

    Is a component that takes in a component(s) as arguments and returns another component.

  3. What are props

    Are inputs to components, they pass data from parent to a child component.

  4. State vs Props

    State are mutable while Props are immutable.

  5. What are synthetic events in React?

    SyntheticEvent is an API same as browser's native event such as preventDefault() and stopPropagation() that works same across all browsers.

  6. Difference between React element and React component

    React element describes what you want to see on the screen(object representation of a DOM node) while React component is a Javascript functions that return JSX.

  7. What is a controlled input element?

    An input element whose value is being controlled by a component’s state

  8. What are refs

    Refs are used to access DOM elements in a DOM. Changes in ref doesn't trigger a component re-render

  9. What are foward refs

    Is a feature that lets you pass/foward a ref to another component

// parent component
import { useRef } from 'react';
import MyInput from './MyInput.js';

export default function Form() {
  const ref = useRef(null);

  function handleClick() {
    ref.current.focus();
  }

  return (
    <form>
      <MyInput label="Enter your name:" ref={ref} />
      <button type="button" onClick={handleClick}>
        Edit
      </button>
    </form>
  );
}

// child component - exposing the DOM to the parent component
import { forwardRef } from 'react';
const MyInput = forwardRef(function MyInput(props, ref) {
  const { label, ...otherProps } = props;
  return (
    <label>
      {label}
      <input {...otherProps} ref={ref} />
    </label>
  );
});
export default MyInput

Conclusion

We've reviewed components in React, their types, performance optimization approaches, HOC like React.memo(). This will give you a general understanding of components in React.

Happy Coding!