close
The Wayback Machine - https://web.archive.org/web/20241213111348/https://www.geeksforgeeks.org/react/
Open In App

React Tutorial

Last Updated : 12 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs) and Virtual DOM for building web applications that are fast, efficient, and scalable.

  • Applications are built using reusable components that enable the reload of only the changed part of the UI. Hence we get a better user experience with React.
  • Allows you to describe how the UI should look based on the state of your application.
  • Uses a virtual DOM to optimize updates, making applications faster and more efficient.
  • Enforces a one-way data flow, making the application predictable and easier to debug.
  • It uses JSX which combines HTML-like syntax with JavaScript's functionality, making it easy to shift to React from JavaScript.

React Tutorial Prerequisites: HTML, CSS and JavaScript

Now Let's see how a Basic React Application looks like

JavaScript
import React from 'react';

function App() {
    return (
        <div>
            <h1>Welcome To React Tutorial</h1>
        </div>
    );
}

export default App;

It will print 'Welcome To React Tutorial' in the Browser.

  • JSX looks like HTML but is JavaScript. <div> and <h1> are React elements created under the hood.
  • Every tag in JSX (like <h1> or <div>) must be properly closed, including self-closing ones like <img />.
  • All returned elements must be inside one parent (e.g., the <div> here).
  • App is a function that returns the UI. It’s exported so it can be used elsewhere.
  • import React from 'react'; is required to use JSX, as JSX is transformed into JavaScript using React.

To Start with React you need to install and setup it on your Machine. Follow these articles to install depending on your system

Now Let's see some of the Core concepts of React

React Components: Building Blocks of React Applications

In React, everything is a component. Components are independent, reusable pieces of code that control a part of the UI. There are two types of components in React:

1. Class Components: These are ES6 classes that extend React.Component.

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

class ClassComponent extends Component {
    render() {
        return <h1>Hello from Class Component!</h1>;
    }
}

export default ClassComponent;

2. Function Components: These are simpler, stateless components that are written as JavaScript functions.

JavaScript
import React from 'react';

const MyComponent = () => {
    return <h1>Hello, React!</h1>;
};

export default MyComponent;
  • Components can accept inputs (called props) and manage their own state.
  • Function components are the modern way of writing React components, especially with the introduction of React Hooks.

JSX: JavaScript Syntax Extension

JSX (JavaScript XML) is a syntax extension for JavaScript that looks similar to HTML. It allows you to write HTML-like code within JavaScript, making it easier to define the structure of your UI.

const element = <h1>Hello, world!</h1>;
  • JSX is not mandatory in React, but it is widely used.
  • JSX gets compiled to React.createElement calls by Babel.
  • You can embed expressions inside JSX by wrapping them in curly braces {}.

React Props: Passing Data to Components

Props (short for properties) are how you pass data to components in React. Props are read-only and allow you to customize components dynamically.

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

// Using the component
<Greeting name="GeeksforGeeks" />

React State: Managing Dynamic Data

State allows React components to manage their own data. Unlike props, which are passed from parent to child, state is managed within the component itself and can change over time.

JavaScript
import React, { useState } from 'react';

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

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

export default Counter;

React Lifecycle Methods: Managing Component Lifecycle

React components go through several lifecycle phases, and you can execute code at specific points during these phases. These phases include

  • Mounting: The component is being created and inserted into the DOM.
  • Updating: The component is re-rendered due to state or props changes.
  • Unmounting: The component is being removed from the DOM.
JavaScript
import React, { Component } from 'react';

class MyComponent extends Component {
    constructor() {
        super();
        console.log('Component created!');
    }

    componentDidMount() {
        console.log('Component mounted!');
    }

    render() {
        return <h1>Lifecycle Methods in React</h1>;
    }
}

export default MyComponent
  • In functional components, React Hooks like useEffect are used to handle lifecycle events.
  • Lifecycle methods are primarily used in class components, but hooks provide a similar effect in function components.

React Hooks: Managing State and Effects in Function Components

With the introduction of React Hooks, function components can now manage state and side effects.

Some of the most commonly used hooks include

  • useState: Adds state to function components.
  • useEffect: Handles side effects like data fetching, event listeners, or subscriptions.
  • useContext: Provides access to context values.
JavaScript
import React, { useState, useEffect } from 'react';

const Timer = () => {
    const [time, setTime] = useState(0);

    useEffect(() => {
        const interval = setInterval(() => {
            setTime((prevTime) => prevTime + 1);
        }, 1000);

        return () => clearInterval(interval);
    }, []);

    return <h1>{time} seconds passed</h1>;
};
  • useEffect can be used to handle side effects like data fetching, DOM manipulation, and subscriptions.
  • Hooks allow you to use state and lifecycle methods in function components.

React Router: Adding Navigation to React Apps

React Router is a popular library for handling routing in React applications. It allows you to navigate between different components without refreshing the page.

JavaScript
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';

const App = () => {
    return (
        <Router>
            <Routes>
                <Route path="/" exact component={Home} />
                <Route path="/about" component={About} />
            </Routes>
        </Router>
    );
};
  • React Router enables single-page navigation in React applications.
  • Use the <Route> component to map URLs to components.
  • <Routes> ensures that only one route is matched at a time.

React State Management: Redux or Context API?

Managing state in large React applications can be complex. While useState and useContext are good for small apps, larger applications might need more robust solutions for state management

  • Redux: A library for managing global state with actions and reducers.
  • Context API: Built-in React API for sharing state between components without prop drilling.

Key Points to consider before choosing between Redux and Context API

  • Use Redux when the app grows larger and requires more control over state changes.
  • Context API is better for passing props at multiple levels in a tree of components.

Why Learn React JS?

React, the popular JavaScript library, offers several exciting reasons for developers to learn it.

  • Flexibility: React allows you to build high-quality user interfaces across different platforms, thanks to its flexible library approach.
  • Great Developer Experience: React makes it easier to write and understand code, offering a smooth development process.
  • Strong Support from Facebook: Regular updates, bug fixes, and resources from Facebook ensure React stays up-to-date and reliable.
  • Vast Community Support: React benefits from a large community, providing enough resources, tutorials, and troubleshooting help.
  • Excellent Performance: React’s efficient Virtual DOM ensures fast rendering and high performance for web applications.
  • Easy Testing: React’s structure and tools make testing simpler, improving code reliability and maintainability.

One of the most effective ways to solidify your understanding is through practical application. That's where structured learning comes into play. For those looking to deepen their React skills and progress from beginner to advanced levels, consider enrolling in the course on React JS: Beginner to Advanced offered by GeeksforGeeks. This comprehensive course provides hands-on projects and real-world applications, making it an excellent resource for anyone serious about mastering React.

Advantages of React

  • Composable: React allows building reusable components, improving code organization and maintainability.
  • Declarative: React’s declarative approach makes it easy to design interactive UIs by changing component states, with React handling the DOM updates.
  • SEO-Friendly: React’s Single Page Application (SPA) setup can be optimized for SEO by rendering and indexing content properly.
  • Large Community: React has a strong community and is widely used by major companies like Meta, Netflix, making it easier to find resources and support.
  • Easy to Learn: React uses JSX, which resembles HTML, making it simple for developers with basic knowledge of HTML, CSS, and JavaScript.
  • Easy Debugging: React’s unidirectional data flow simplifies debugging by ensuring that data moves in a clear, predictable direction within components.

If you want to learn more refer to this article React JS Advantages

React Basic Concepts

Introduction to the Fundamentals of React form importing, exporting modules, creating components, to managing data flow and rendering UI across the application.

React Hooks

Different hooks to access and mange state and lifecycle in functional components.

React DOM Events

Handle DOM events in react like mouse, keyboard and form events.

Lifecycle of Components

The lifecycle of react components from creation, mounting and unmounting to manage the different phases.

Routing in React

Manage navigation and routing within the single page application.

Important React Packages

Additional libraries for styling and state management to enhance your react projects.

React Interview Questions

React Interview questions categorised for different levels including most asked questions.

React Online Quizs

Test and Improve your knowledge with the well organised React Quizs

React Online Practice Exercise

Embark on your React learning journey with our online practice portal. Start by selecting quizzes tailored to your skill level. Engage in hands-on coding exercises, receive real-time feedback, and monitor your progress. With our user-friendly platform, mastering React becomes an enjoyable and personalized experience.

Elevate your coding expertise by going through our carefully curated Free Online React Exercises.

React Complete References

Refer to the following articles to have a quick glance at all the important key concepts which are helpful while developing web applications using React

If you want to have a simple, quick reference to commonly used React methods you can refer to ReactJS Cheat Sheet article

React is a JavaScript library for building user interfaces, focusing on component-based architecture, reusability, and efficient rendering with the virtual DOM. This React tutorial covers essential topics like JSX, components, hooks, state management, routing with React Router, and popular libraries like Redux and Material UI. It also includes quizzes and interview questions to reinforce and test your knowledge.

React Tutorial - FAQ's

What is React used for?

The primary goal of React is to create a User Interface, Single-Page Application, Progressive Web Application and more.

Which language is used in React?

React used JavaScript programming language.

Is React a front-end language?

React globally used for Front-end JS library and it is popular with both software and project speoncer.

Which is in demand ReactJS or AngulerJS in 2024?

React is far more popular than AngulerJS because ReactJS comes with more libraries, resources and bigger community support.

Which is better NodeJS or ReactJS or AngularJS

Choosing the framework always depends very much on your requirements. All of these three frameworks are quite popular, and users choose them based on what they want to do. But if we do so more specifically, then ReatJS is better.

Is this ReactJS tutorial for beginners or for advanced

As we said at the beginning of this article, this course is for beginners as well as for advanced. 


Similar Reads

Article Tags :
three90RightbarBannerImg