DEV Community

loading...
Cover image for Understanding React Components.

Understanding React Components.

ReenyDavidson
・6 min read

React is a frontend UI library for designing user interfaces of web applications.

When writing a React application, it is very necessary you understand the concept of React components and what they actually do. React has made these components very easy to create and very much reusable in any case.

Now lets jump into Components, shall we?

What are React Components?

React components are independent units that make up a React app. It can also be seen as building blocks that evaluates to a full React application. You would definitely be using components a lot, trust me. In fact, you cannot build a React application without creating components, it’s impossible. Imagine building a house without blocks or building a car without it’s various parts, that is very impossible. These components must be put together to build a React application. They make up different part of the UI and also let you control all these parts independently.

const myFirstComponent = () => <h1>Yes! I wrote a component</h1>
Enter fullscreen mode Exit fullscreen mode

The above is a very simple function component that will display the h1 child to the browser. Mind you, the element that is being returned by the component above is not HTML. It is called JSX. Visit here for better understanding of JSX


Types of Components

In React, there are basically two types of components. These two types of components are:

  1. Class components
  2. Functional components

I will start by explaining the class component.

Class Components (stateful)

The class component is said to be stateful as it tends to implement some kind of logic and also manage any local state in the component. It also accepts lifecycle methods.

import React from "react";

const FunctionComponent = (props) => {
  return (
    <div>
      <form>
        <input placeholder="Enter Term..." />
        <button>Submit</button>
      </form>
      <div>
        <h1>{props.message}</h1>
      </div>
    </div>
  );
};

export default FunctionComponent;

Enter fullscreen mode Exit fullscreen mode

A simple class component in react.


state

React state can be seen as an instance of properties that affects the behavior of the UI when rendered to the browser. It handles data that changes overtime, which means it is mutable. The state is basically an object that holds some kind of data that affects the UI at anytime. This state can only be written in a class component.

import React, { Component } from "react";

class App extends Component {
  state={firstname:'', lastname:''}

  render(){
    return (
      <div>
      <form>
        <input
          placeholder='firstname'
          value={this.state.firstname}
          onChange={(e)=>{this.setState({firstname:e.target.value})}}
        />
         <input
          placeholder='lasttname'
          value={this.state.lastname}
          onChange={(e)=>{this.setState({lastname:e.target.value})}}
        />
        <button onClick={(e)=>{e.preventDefault()}}>click</button>
      </form>

</div>
    )
  }
}

export default App

Enter fullscreen mode Exit fullscreen mode

A class component with state.

The above code shows that on every keypress on the form input, the component re-renders and changes the UI state.

Lifecycle methods

Lifecycle methods simply explains the all round period of the component from when it was rendered to when it was destroyed, probably as a result of leaving page or deleting something. Just like a cooking process or lifecycle, components has its own lifecycle. The three major ones are:

  1. When the component mounts

  2. When the component updates

  3. When the component unmounts.

componentDidMount

This method is called once. It is fired immediately the component has been rendered. You can use this method to fetch data from an API and also render the data after the component has been mounted. You can use it to fetch any information or data you want to have immediately the component is rendered.

componentDidMount() {
       console.log('I run immediately the component is rendered')
  }
Enter fullscreen mode Exit fullscreen mode

The above code will log “I run immediately the component is rendered” to the console immediately the component is rendered.

componentDidUpdate

This method is called when there’s a change in the state of a rendered component. This method accepts two arguments which are the previous props and the previous state.

componentDidUpdate(prevProps, prevState) {
  if (prevState.colors !== this.state.colors) {
    console.log('colors has changed.')
  }
}

Enter fullscreen mode Exit fullscreen mode

Basically, componentDidUpdate is called based on a condition that is to be met, which is a comparison between the previous state and current state. If there is a change from previous state to current state, the method will run, but if no change has occurred in the state, the method won’t be called.

componentWillUnmount

This method is called when the component is being removed from the DOM. It is the last method you call in a component’s lifecycle. Basically, you call this guy to run immediately before the component is destroyed and in this method, you can do some cleanup that regards to the component before it unmounts.

componentWillUnmount(){
    alert('This component is about to be unmounted.');
}
Enter fullscreen mode Exit fullscreen mode

In the above snip, we can see that the user is getting a warning from componentWillUnmount before the component is destroyed. Basically, componentWillUnmount holds the activity that will be carried before the component is dismantled from the DOM.


Functional Components (I am without state)

Also known as stateless component is a component that only takes in props and renders elements (JSX) to the UI. A functional component cannot manage state, making it impossible for it to implement any form of logic that might affect the state of the UI being rendered. It is basically a Javascript function returning an element.

import React from "react";

const FunctionComponent = (props) => {
  return (
    <div>
      <form>
        <input placeholder="Enter Term..." />
        <button>Submit</button>
      </form>
      <div>
        <h1>{props.message}</h1>
      </div>
    </div>
  );
};

export default FunctionComponent;

Enter fullscreen mode Exit fullscreen mode

Function Component in React.

The code above shows a function component that takes in an input element and a props which is basically passing information from another component. Apart from the fact that a function component returns JSX and accepts props, We can also say that function component is used only when we have no plan to make use of state and lifecycle methods in the component. BUT! let’s not write this guy off yet, he has his own super powers which he uses to effect changes to the UI.

Function component uses what is known as Hooks to effect changes to UI. Hooks lets you hook into React state in a function component with useState and also tap into lifecycle method with useEffect. Hooks makes it possible for logic to be applied in a function component. It is a very important tool in React function components.

UseState

UseState hook basically does in function component what a state and setState would do in class component, which is manipulating the UI.

import React from "react";

const FunctionalInput = () => {
  const [state, setstate] = React.useState({ firstname: "", lastname: "" });
  const handleClick = (e) => {
    setstate(e.target.value);
    console.log(e.target.value);
  };

  return (
    <div>
      <input
        value={state.firstname}
        onChange={handleClick}
        placeholder="firstname"
      />
      <input
        value={state.lastname}
        onChange={handleClick}
        placeholder="lastname"
      />
    </div>
  );
};

export default FunctionalInput;

Enter fullscreen mode Exit fullscreen mode

use of useState in a function component

The code above shows how React uses useState to manage state in a function component. In the array destructuring seen above, ‘state’ is the initial condition of the UI and we need to update that at every keypress made in the input element which re-renders the UI and also changes the state of the UI at every re-render. I came to realize that useState does a better job at managing state (just my opinion). I believe so because it just use less code to do the same thing that the class component does with setState.

useEffect

Another hook we will look at is the useEffect hook. It has some kind of similarity with the the lifecycle methods of the class component. This hook is basically a function that holds another function that will run after the the UI has been rendered, just like componentDidMount would do. It also does it with less code, unlike lifecycle methods that involves componentDidMount, componentDidUpdate and componentWillUnmount just to do what only useEffect will do.

import React, { useEffect } from "react";

const FunctionalInput = () => {
  const [state, setstate] = React.useState({ firstname: "", lastname: "" });

  //This piece of code runs after the ui has been rendered
  useEffect(() => {
    console.log("A component was rendered!!!");
  }, []);

  const handleClick = (e) => {
    setstate(e.target.value);
    console.log(e.target.value);
  };

  return (
    <div>
      <input
        value={state.firstname}
        onChange={handleClick}
        placeholder="firstname"
      />
      <input
        value={state.lastname}
        onChange={handleClick}
        placeholder="lastname"
      />
    </div>
  );
};

export default FunctionalInput;

Enter fullscreen mode Exit fullscreen mode

use of useEffect in a function component

useEffect here will run immediately the UI is rendered. The array at the end makes it run once and never run again at every re-render, but without the array, useEffect continues to run each time the UI re-renders. An API can also be fetched with useEffect hook. When the UI renders, the useEffect is triggered, which allows the API to retrieve any form of data it is meant to retrieve.

In React, you can create your own custom hooks, which gives you the freedom to use hooks as you please. Note that React Hooks can only be used in React function component.

These two components mentioned in this article can be used, based on what you are building. It’s very necessary you learn how to use the two of them as a React developer.

With that being said, go and React!

Discussion (0)

Forem Open with the Forem app