React

JavaScript library for building user interfaces developed by Facebook. Component-based design enables creating reusable and maintainable UIs.

JavaScriptFrameworkFrontendUIComponentsVirtual DOM

Framework

React

Overview

React is a JavaScript library for building user interfaces, developed by Facebook.

Details

React is a declarative, efficient, and flexible JavaScript library that was open-sourced by Facebook in 2013. It adopts a component-based architecture for building UIs, allowing you to create reusable UI components. By using Virtual DOM, a virtual representation of the DOM, React minimizes actual DOM manipulation and achieves high performance. With unidirectional data flow and state management, it enables predictable and maintainable application development. JSX syntax extension allows you to define components with HTML-like notation, improving developer experience. Currently, React has the world's largest frontend ecosystem and is used in combination with many related technologies such as Next.js, Gatsby, and React Native.

Code Examples

Hello World

// Basic functional component
function HelloWorld() {
  return <h1>Hello, React!</h1>;
}

// Arrow function notation
const HelloWorld = () => {
  return <h1>Hello, React!</h1>;
}

// Rendering
import ReactDOM from 'react-dom/client';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<HelloWorld />);

Components and Props

// Component receiving Props
function Welcome(props) {
  return <h1>Hello, {props.name}!</h1>;
}

// Using destructuring assignment
function Welcome({ name, age }) {
  return (
    <div>
      <h1>Hello, {name}!</h1>
      <p>You are {age} years old.</p>
    </div>
  );
}

// Usage example
function App() {
  return (
    <div>
      <Welcome name="John" age={25} />
      <Welcome name="Jane" age={30} />
    </div>
  );
}

State Management (useState)

import { useState } from 'react';

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

  const increment = () => {
    setCount(count + 1);
  };

  const decrement = () => {
    setCount(count - 1);
  };

  return (
    <div>
      <h2>Counter: {count}</h2>
      <button onClick={increment}>+1</button>
      <button onClick={decrement}>-1</button>
      <button onClick={() => setCount(0)}>Reset</button>
    </div>
  );
}

Effects (useEffect)

import { useState, useEffect } from 'react';

function UserProfile({ userId }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // Data fetching
    const fetchUser = async () => {
      setLoading(true);
      try {
        const response = await fetch(`/api/users/${userId}`);
        const userData = await response.json();
        setUser(userData);
      } catch (error) {
        console.error('Failed to fetch user data:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchUser();
  }, [userId]); // Re-run when userId changes

  if (loading) return <div>Loading...</div>;
  if (!user) return <div>User not found</div>;

  return (
    <div>
      <h2>{user.name}</h2>
      <p>Email: {user.email}</p>
    </div>
  );
}

Form Handling

import { useState } from 'react';

function ContactForm() {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    message: ''
  });

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log('Form data:', formData);
    // API submission logic
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="name">Name:</label>
        <input
          type="text"
          id="name"
          name="name"
          value={formData.name}
          onChange={handleChange}
          required
        />
      </div>
      <div>
        <label htmlFor="email">Email:</label>
        <input
          type="email"
          id="email"
          name="email"
          value={formData.email}
          onChange={handleChange}
          required
        />
      </div>
      <div>
        <label htmlFor="message">Message:</label>
        <textarea
          id="message"
          name="message"
          value={formData.message}
          onChange={handleChange}
          rows={4}
          required
        />
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

Custom Hooks

import { useState, useEffect } from 'react';

// Custom hook: Data fetching
function useApi(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        const response = await fetch(url);
        if (!response.ok) {
          throw new Error('Failed to fetch data');
        }
        const result = await response.json();
        setData(result);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [url]);

  return { data, loading, error };
}

// Usage example of custom hook
function ProductList() {
  const { data: products, loading, error } = useApi('/api/products');

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error}</div>;

  return (
    <ul>
      {products?.map(product => (
        <li key={product.id}>
          {product.name} - ${product.price}
        </li>
      ))}
    </ul>
  );
}

Advantages and Disadvantages

Advantages

  • Component-based: Reusable UI components improve maintainability
  • Virtual DOM: High performance and efficient rendering
  • Rich Ecosystem: Vast library and tool ecosystem
  • Learning Community: World's largest developer community
  • Corporate Support: Continuous development and support by Meta (Facebook)
  • TypeScript Support: Enhanced developer experience with type safety
  • React DevTools: Excellent development and debugging tools

Disadvantages

  • Learning Curve: Many concepts to master including JSX, hooks, state management
  • Rapid Changes: Frequent updates and changing best practices
  • Configuration Complexity: Complex setup required for production projects
  • SEO Challenges: Search engine optimization issues with Client-Side Rendering
  • Bundle Size: Bundle size growth in large-scale applications

Key Links