Getting Started with React

Ganesh JaiwalGanesh Jaiwal
4 min read

React is an incredibly popular JavaScript library for building user interfaces, particularly for single-page applications where responsive user experience is crucial. Developed and maintained by Facebook, React allows developers to create large web applications that can change data, without reloading the page. This blog post will delve into the fundamental concepts of React, helping you understand the core elements: components, JSX, rendering elements, props, state, lifecycle methods, and hooks such as useState and useEffect.

Understanding React Components

At its core, React is based on components, which are the building blocks of any React application. Components can be thought of as independent, reusable pieces of code that encapsulate both the behavior and appearance of a part of the user interface.

Functional vs Class Components

In React, components can be classified into two types: functional components and class components.

  • Functional Components: These are JavaScript functions that return JSX. They are known for being simpler and have less boilerplate than class components. Starting with the introduction of Hooks in React 16.8, functional components can manage their state and lifecycle features, making them powerful and versatile.
// Functional Component
function Welcome(props) {
    return <h1>Hello, {props.name}!</h1>;
}
  • Class Components: These are ES6 classes that extend from React.Component. They must include a render method that returns JSX. Class components allow you to use lifecycle methods, making them suitable for applications that require component state management and more complex behavior.
// Class Component
class Welcome extends React.Component {
    render() {
        return <h1>Hello, {this.props.name}!</h1>;
    }
}

Summary

While class components still have their use cases, the React community is increasingly favoring functional components due to their simplicity and the introduction of Hooks, which facilitate state and lifecycle management in a more straightforward manner.

JSX: JavaScript XML

JSX stands for JavaScript XML, and it is a syntax extension for JavaScript that resembles HTML. JSX allows developers to write HTML-like structures directly in their JavaScript code, greatly enhancing the readability and clarity of code.

Example of JSX

const element = <h1>Hello, world!</h1>;

The above code creates a React element that can be rendered easily. Under the hood, JSX gets transpiled into plain JavaScript via tools like Babel.

Important Points About JSX:

  • It allows you to embed expressions within curly braces {}.

  • You can nest elements just as you would in HTML.

  • For attributes, JSX uses camelCase (e.g., className instead of class).

const element = <div className="header">Welcome to my App!</div>;

Rendering Elements

To render elements and components to the DOM, you can use the ReactDOM.render() method.

ReactDOM.render(<Welcome name="Alice" />, document.getElementById('root'));

This code takes the component Welcome and renders it inside an HTML element with the ID of root.

Props: Passing Data to Components

Props (short for properties) are a mechanism for passing data from one component to another in React. Props are read-only and are passed from a parent component to a child component. This makes it easier to manage the flow of data and promote component reusability.

Example of Using Props

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

ReactDOM.render(<Greeting name="Alice" />, document.getElementById('root'));

In this example, the Greeting component receives a name prop from the parent and renders it within an h1 tag.

State and Lifecycle Methods

In addition to props, components can also maintain their own internal state. State provides a way to store property values over time and allows your application to respond to user input and other events dynamically.

Introduction to useState

The useState hook is used to declare state variables in functional components. You can think of state as a component's local storage that determines how the component appears on the screen.

import React, { useState } from 'react';

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

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

In this example, clicking the button increments count by 1, demonstrating how state changes trigger re-renders.

Introduction to useEffect

The useEffect hook allows you to perform side effects in your function components, such as fetching data, subscribing, or manually changing the DOM.

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

function UserProfile() {
    const [user, setUser] = useState(null);

    useEffect(() => {
        fetch('https://api.example.com/user')
            .then(response => response.json())
            .then(data => setUser(data));
    }, []); // The empty array means this effect runs once, after the first render.

    if (!user) {
        return <div>Loading...</div>;
    }

    return <div>{user.name}</div>;
}

In this example, when the UserProfile component mounts, it fetches user data from an API and updates the state when the data is received.

Conclusion

React provides a powerful and flexible framework for building modern web applications. Understanding the fundamental concepts of components, JSX, rendering, props, state, and lifecycle methods will give you a solid foundation for creating interactive user interfaces. As you build more complex applications, the concepts of hooks like useState and useEffect will become your best friends in managing state and side effects effectively.

With practice and experimentation, you'll soon be well on your way to mastering React and building dynamic web applications that impress your users. Happy coding!

1
Subscribe to my newsletter

Read articles from Ganesh Jaiwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ganesh Jaiwal
Ganesh Jaiwal

Hello! I'm a dedicated software developer with a passion for coding and a belief in technology's impact on our world. My programming journey started a few years ago and has reshaped my career and mindset. I love tackling complex problems and creating efficient code. My skills cover various languages and technologies like JavaScript, Angular, ReactJS, NodeJs, and Go Lang. I stay updated on industry trends and enjoy learning new tools. Outside of coding, I cherish small routines that enhance my workday, like sipping tea, which fuels my creativity and concentration. Whether debugging or brainstorming, it helps me focus. When I'm not coding, I engage with fellow developers. I value teamwork and enjoy mentoring newcomers and sharing my knowledge to help them grow. Additionally, I explore the blend of technology and creativity through projects that incorporate art and data visualization. This keeps my perspective fresh and my passion alive. I'm always seeking new challenges, from open-source contributions to hackathons and exploring AI. Software development is more than a job for me—it's a passion that drives continuous learning and innovation.