Home > ReactJS > How to Create Components in ReactJS?

How to Create Components in ReactJS?

Welcome, fellow React enthusiasts! If you’re diving into the world of ReactJS, understanding how to create components is an essential first step. Components lie at the heart of React development, empowering you to build dynamic, reusable UI elements with ease.

In this comprehensive guide, we’ll walk through everything about how you can create components in ReactJS, from the basics to advanced techniques. Also about react hooks and lifecycle methods and state management in components.

Understanding Components in ReactJS

ReactJS is based on the concept of components. A component is basically a building block that contains a piece of UI functionality. You can create multiple components in React. You can use components to create buttons, forms, or even entire page layouts. Breaking down your UI into smaller, manageable components can make your code more organized and easy to maintain.

In React, there are two primary types of components: functional components and class components.

Functional Components

These are simple JavaScript functions that accept props (short for properties) as arguments and return React elements to describe what should appear on the screen. Functional components have become increasingly popular due to their simplicity and the introduction of React Hooks, which allow functional components to manage state and side effects.

Class Components

Class components are ES6 classes that extend from React.Component. While functional components are preferred for their simplicity, class components are still widely used, especially in legacy codebases. Class components have their state and lifecycle methods, making them more suitable for complex logic and interactions.

Create a Functional Component

Let’s start by creating a simple functional component in ReactJS. Below is an example of a basic functional component that renders a greeting message.

import React from 'react';

const Greeting = (props) => {
  	return <h1>Hello, {props.name}!</h1>;
};

export default Greeting;

Use this Function Component

<Greeting name='Aman Mehra' />
// Output
Hello, Aman Mehra

In this example, we define a functional component called Greeting that accepts a name prop to render a greeting message using JSX. Then we call that component by passing the name props with value and get the output.

React Hooks

Functional components don’t have lifecycle methods like class components (we will see below), the introduction of React Hooks in React 16.8 opened up new possibilities for managing side effects and component lifecycle in functional components.

There are many React hooks like useState, useEffect, useMemo, useRef, useSelector, etc. You can also create your own custom hook.

useState() Hook

The useState hook is commonly used to manage the state. It allows functional components to have a local state. It takes an initial state as an argument and returns a stateful value and a function to update it.

import React, { useState } from 'react';

const Counter = () => {
  	const [count, setCount] = useState(0);

  	return (
    	<div>
      		<p>Count: {count}</p>
      		<button onClick={() => setCount(count + 1)}>Increment</button>
    	</div>
  	);
};

export default Counter;

In this example, the useState hook is used to create a count state variable and a setCount function to update it.

You can check the complete details guide by following this link React useState Hook Tutorial.

useEffect() Hook

The useEffect hook allows functional components to perform side effects, such as data fetching, subscriptions, or manually changing the DOM, after the component has rendered.

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const DataFetcher = () => {
	const [data, setData] = useState(null);

  	useEffect(() => {
    	axios.get('https://api.example.com/data')
      	.then(data => setData(data));
  	}, []);

  	return (
    	<div>
      		{data ? (
        		<p>Data: {data}</p>
      		) : (
        		<p>Loading...</p>
      		)}
    	</div>
  	);
};

export default DataFetcher;

In this example, the useEffect hook fetches data from an API using the axios.get() when the component is mounted to the DOM (thanks to the empty dependency array []) and updates the data state.

For more details, you can check the complete guide on React useEffect Hook.

Create a Class Component

As I said, class components are ES6-based classes that extend from React.Component. Let’s create the same <Greeting> component using a class component with the ES6 approach.

import React, { Component } from 'react';

class Greeting extends Component {
  	render() {
    	return <h1>Hello, {this.props.name}!</h1>;
  	}
}

export default Greeting;

Use this Class Component

<Greeting name='Aman Mehra' />
// Output
Hello, Aman Mehra

Here, we define a class component Greeting that extends React.Component and implements a render method to return the JSX markup. Did you notice that, here we used the ‘this’ keyword to get the props value.

Lifecycle Methods

Class components in React come with a set of lifecycle methods that allow you to hook into different phases of a component’s lifecycle. These methods can be useful for performing actions such as initializing the state, fetching data from a server, or cleaning up resources.

The class component has also different methods for different purposes. Like componentDidMount(), getDerivedStateFromProps(), componentDidUpdate(), shouldComponentUpdate(), etc.

componentDidMount() Method

The componentDidMount() method is called after the component has been rendered to the DOM. It’s commonly used for fetching data from a server or initializing third-party libraries.

import React, { Component } from 'react';
import axios from 'axios';

class DataFetcher extends Component {
	constructor(props) {
    	super(props);
    	this.state = { data: null };
	}

	componentDidMount() {
  		axios.get('https://api.example.com/data')
        	.then(response => {
          		this.setState({ employees: response.data });
        	});
  	}

  	render() {
    	return (
      		<div>
        	{this.state.data ? (
          		<p>Data: {this.state.data}</p>
        	) : (
          		<p>Loading...</p>
        	)}
      	</div>
    	);
  	}
}

export default DataFetcher;

In this example, the DataFetcher component fetches data from an API using the axios.get() when it’s mounted to the DOM.

componentDidUpdate() Method

The componentDidUpdate() method is called after the component’s updates are flushed to the DOM. It’s useful for reacting to prop or state changes and performing side effects based on those changes.

import React, { Component } from 'react';

class Logger extends Component {
  	componentDidUpdate(prevProps, prevState) {
    	console.log('Props:', this.props);
    	console.log('State:', this.state);
  	}

  	render() {
    	return <p>Logger Component</p>;
  	}
}

export default Logger;

In this example, the Logger component logs the current props and state to the console whenever it updates.

Also Read: Higher Order Components in React

Props and State Management in Components

In React, props and state are two fundamental concepts for managing data within components.

Props

Props (short for properties) are read-only data that are passed from a parent component to a child component. They allow you to customize the behavior and appearance of a component dynamically. You can also conditionaly add props to components.

// Parent Component
import React from 'react';
import Greeting from './Greeting';

const App = () => {
  	return <Greeting name="John" />;
};

export default App;

In this example, we import the Greeting component and then pass a name props with the value “John” to the Greeting component.

State

State, on the other hand, is data that is managed within a component and can be changed over time. Stateful components have an internal state that determines their behavior and appearance.

import React, { Component } from 'react';

class Counter extends Component {
  	constructor(props) {
    	super(props);
    	this.state = { count: 0 };
  	}

  	render() {
    	return (
      		<div>
        		<p>Count: {this.state.count}</p>
        		<button onClick={() => this.setState({ count: this.state.count + 1 })}>Increment</button>
      		</div>
    	);
  	}
}

export default Counter;

In this example, we define a Counter component with an internal state count, which gets incremented each time when the button is clicked.

Conclusion

Congratulations! You’ve now learned about how to create components in ReactJS from basic to advanced. Components are the building blocks of React applications, allowing you to create reusable UI elements efficiently. Whether you’re building simple UI widgets or complex application interfaces, mastering components is essential for becoming proficient in React development.

FAQs

What are the components in ReactJS, and why are they important?

Components are essential building blocks in ReactJS, breaking down UI into reusable pieces, and promoting code reusability, maintainability, and scalability.

What is the difference between functional components and class components?

Functional components are simple functions, preferred for their simplicity and compatibility with React Hooks, while class components are ES6 classes with their state and lifecycle methods.

How do you pass data between components in ReactJS?

Data is passed between components using props, allowing dynamic customization of a component’s behavior and appearance.

What are lifecycle methods, and how do they work in ReactJS?

Lifecycle methods are hooks into different phases of a component’s lifecycle. Class components have methods like componentDidMount and componentWillUnmount, while functional components use hooks like useEffect to perform similar tasks.

How to optimize the React component’s performance?

To optimize performance, minimize re-renders with PureComponent or memoization, use React DevTools for profiling, implement code-splitting, avoid unnecessary state updates, optimize component size, leverage virtualization, and use production builds.

Photo of author

About Aman Mehra

Hey there! I'm Aman Mehra, a full-stack developer with over six years of hands-on experience in the industry. I've dedicated myself to mastering the ins and outs of PHP, WordPress, ReactJS, NodeJS, and AWS, so you can trust me to handle your web development needs with expertise and finesse. In 2021, I decided to share my knowledge and insights with the world by starting this blog. It's been an incredible journey so far, and I've had the opportunity to learn and grow alongside my readers. Whether you're a seasoned developer or just dipping your toes into the world of web development, I'm here to provide valuable content and solutions to help you succeed. So, stick around, explore the blog, and feel free to reach out if you have any questions or suggestions. Together, let's navigate the exciting world of web development!

Leave a Comment