How To Use React JS

How To Use React JS

How To Use React JS

React JS has revolutionized front-end development by enabling developers to create fast, dynamic, and interactive user interfaces with ease. Whether you're new to web development or an experienced JavaScript developer looking to enhance your skills, understanding how to use React JS effectively is essential.

In this comprehensive guide, we'll walk you through what React JS is, why it's so popular, and how you can start building modern web applications with it. You'll also learn about essential tools, setup steps, components, and best practices to master React development.

What Is React JS?

React JS, commonly referred to as React, is an open-source JavaScript library created by Facebook. It is primarily used for building user interfaces (UI) and handling the view layer of web applications. React allows developers to create reusable UI components that manage their own state, making applications more efficient and easier to maintain.

React is component-based, declarative, and flexible --- three qualities that make it one of the most powerful tools for front-end development.

Why Choose React JS?

React has become the go-to library for developers and businesses worldwide. Here's why it stands out:

1. Component-Based Architecture

React divides the UI into small, reusable components. This modular structure makes it easy to build complex UIs and maintain consistency across applications.

2. Virtual DOM for Performance

React uses a Virtual DOM to optimize rendering. Instead of reloading the entire page, React updates only the components that have changed, resulting in faster performance and a smoother user experience.

3. Declarative Syntax

React's declarative style makes code more predictable and easier to debug. You describe what the UI should look like, and React takes care of the rest.

4. Strong Community Support

Since its release, React has gained massive community support, extensive documentation, and a wealth of third-party libraries that speed up development.

5. Ecosystem Integration

React works seamlessly with other technologies in the MERN stack (MongoDB, Express, React, Node.js), making it a preferred choice for full-stack JavaScript developers.

Setting Up a React JS Project

Getting started with React JS is simple. Follow these steps to set up your first React project:

Step 1: Install Node.js and npm

Before using React, ensure that you have Node.js installed. You can check by running the following command in your terminal:

node -v
npm -v

If not installed, download it from Node.js official website.

Step 2: Create a React App

The easiest way to start with React is by using Create React App, a command-line tool provided by the React team.

npx create-react-app my-react-app
cd my-react-app
npm start

Your app will open in the browser at http://localhost:3000, displaying the default React welcome screen.

Step 3: Understand Project Structure

After creating your app, you'll see folders and files like:

my-react-app/
├── node_modules/
├── public/
├── src/
│   ├── App.js
│   ├── index.js
│   └── App.css
├── package.json
└── README.md
  • src/: Contains your React components and logic.
  • public/: Contains static assets like images or favicon.
  • package.json: Manages dependencies and scripts.

Understanding React Components

React applications are built using components --- small, reusable pieces of UI.

1. Functional Components

A functional component is a JavaScript function that returns JSX (JavaScript XML).

function Welcome() {
  return <h1>Hello, React!</h1>;
}

2. Class Components

Before hooks were introduced, class components were used to manage state and lifecycle methods.

class Welcome extends React.Component {
  render() {
    return <h1>Hello, React!</h1>;
  }
}

3. JSX Syntax

JSX allows you to write HTML-like syntax inside JavaScript:

const element = <h1>Welcome to React!</h1>;

Behind the scenes, JSX is transformed into React's createElement function.

State and Props in React

React components use state and props to manage and pass data.

Props (Properties)

Props are used to pass data from parent to child components.

function Greeting(props) {
  return <h1>Hello, {props.name}</h1>;
}
<Greeting name="Bilal" />

State

State allows components to manage internal data that changes over time.

function Counter() {
  const [count, setCount] = React.useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click Me</button>
    </div>
  );
}

Here, useState is a React hook used to add state to functional components.

Handling Events in React

React supports standard JavaScript events with slight syntactical changes. Event names use camelCase, and you pass functions as event handlers.

<button onClick={handleClick}>Click Me</button>

Example:

function handleClick() {
  alert("Button Clicked!");
}

React Lifecycle Methods

Every React component goes through stages called lifecycle methods --- mounting, updating, and unmounting. These methods allow you to perform actions at specific points in a component's existence.

Common lifecycle methods include:

  • componentDidMount() -- Runs after the component is rendered.
  • componentDidUpdate() -- Runs after an update occurs.
  • componentWillUnmount() -- Runs before the component is destroyed.

With hooks, these are replaced by the useEffect hook.

Using useEffect Hook

The useEffect hook allows you to handle side effects in React --- like fetching data, updating the DOM, or setting timers.

import React, { useState, useEffect } from "react";

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

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then((response) => response.json())
      .then((data) => setData(data));
  }, []);

  return (
    <ul>
      {data.map((item) => (
        <li key={item.id}>{item.title}</li>
      ))}
    </ul>
  );
}

The empty array [] ensures the effect runs only once after the initial render.

Routing in React with React Router

React doesn't include built-in routing, but you can use React Router to handle navigation between pages.

npm install react-router-dom

Example setup:

import { BrowserRouter as Router, Route, Routes, Link } from "react-router-dom";

function App() {
  return (
    <Router>
      <nav>
        <Link to="/">Home</Link>
        <Link to="/about">About</Link>
      </nav>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </Router>
  );
}

Styling in React

You can style React components in multiple ways:

  • CSS Files: Import traditional CSS files.
  • Inline Styles: Apply styles directly using objects.
  • CSS Modules: Scoped CSS for components.
  • Styled Components: CSS-in-JS using libraries like styled-components.

Example:

const buttonStyle = {
  backgroundColor: "blue",
  color: "white",
  padding: "10px 20px",
};

function StyledButton() {
  return <button style={buttonStyle}>Click Me</button>;
}

Working with APIs in React

Fetching data from APIs is common in React apps. You can use the native fetch API or libraries like axios.

npm install axios

Example using Axios:

import axios from "axios";
import { useEffect, useState } from "react";

function Users() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    axios.get("https://jsonplaceholder.typicode.com/users")
      .then((response) => setUsers(response.data));
  }, []);

  return (
    <ul>
      {users.map(user => <li key={user.id}>{user.name}</li>)}
    </ul>
  );
}

Best Practices for React Development

To write clean, efficient React code, follow these practices:

  1. Use Functional Components with hooks instead of class components.
  2. Keep Components Small and Reusable --- each should handle one responsibility.
  3. Use Keys When Rendering Lists to maintain stability.
  4. Optimize Performance with memoization (React.memo, useMemo, useCallback).
  5. Use PropTypes or TypeScript for type checking.
  6. Keep State Local Where Possible and lift only when necessary.
  7. Avoid Direct DOM Manipulation --- React handles it internally.

Deploying a React Application

Once your app is ready, it's time to deploy.

Step 1: Build Your App

npm run build

Step 2: Deploy to Hosting Platform

You can deploy on platforms like Vercel, Netlify, or GitHub Pages. Upload the build/ folder, and your React app will be live.

Final Thoughts

Learning how to use React JS opens the door to creating fast, responsive, and scalable web applications. With its strong ecosystem and active community, React continues to dominate modern web development.

If you're planning to build a high-performance MERN Stack application, you can AAMAX --- a full-service digital marketing company offering professional Web Development, Digital Marketing, and SEO Services. The AAMAX team has extensive expertise in React JS and full-stack JavaScript development, ensuring your business website or app is modern, secure, and growth-oriented.

Related Blogs

How To Deploy MERN App on Netlify

How To Deploy MERN App on Netlify

Deploying a MERN (MongoDB, Express.js, React, Node.js) application can be a challenging task for many developers, especially when it comes to choosing...

How To Learn React JS

How To Learn React JS

React JS has revolutionized front-end web development with its component-based architecture, virtual DOM, and vast ecosystem. Whether you’re a beginne...

How To Deploy MERN App on Heroku

How To Deploy MERN App on Heroku

MERN (MongoDB, Express, React, Node.js) application is an exciting journey, but once your app is ready, deployment becomes the next big step. Deployin...

How To Host MERN Stack Website

How To Host MERN Stack Website

Hosting a MERN stack website — which combines MongoDB, Express.js, React, and Node.js — can seem intimidating at first, especially if you’re new to fu...

How To Push MERN Stack Project on Github

How To Push MERN Stack Project on Github

Pushing your MERN Stack project (MongoDB, Express.js, React, and Node.js) to GitHub is one of the most essential steps in modern web development. It a...

How To Use React JS

How To Use React JS

React JS has revolutionized front-end development by enabling developers to create fast, dynamic, and interactive user interfaces with ease.

Need Help? Chat with Our AI Support Bot