Skip to main content
FREE Mock interview & resume review with Sumit. Free right now, no payment needed.Book a slot

React JS Complete Learning

Build modern user interfaces with React. The complete guide for beginners.

jiocoder TeamUpdated Jun 6, 20265 min readReact
React JS Complete Learning

What is React?#

React is a free and open-source JavaScript library for building user interfaces, particularly single-page applications and mobile applications. It was created by Jordan Walke, a software engineer at Facebook, and was first released in 2013. React is maintained by Meta (formerly Facebook) and a community of individual developers and companies.

Key Features of React#

  • Component-Based - Build encapsulated components that manage their own state
  • Declarative - Describe what the UI should look like, React handles the updates
  • Virtual DOM - Efficient rendering by updating only changed parts
  • One-Way Data Flow - Data flows down from parent to child components
  • Reusable Components - Write once, use anywhere
  • Rich Ecosystem - Large community and extensive library support

Setting Up React#

You can create a new React app using Create React App or Vite:

Code
# Using Create React App
npx create-react-app my-app
cd my-app
npm start

# Using Vite (faster)
npm create vite@latest my-app -- --template react
cd my-app
npm install
npm run dev

Components#

Components are the building blocks of React applications. They let you split the UI into independent, reusable pieces. There are two types of components:

Code
// Simple functional component
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

// Arrow function component
const Greeting = ({ name }) => {
  return <div>Welcome, {name}!</div>;
};

// Component with multiple elements
const Card = ({ title, content }) => {
  return (
    <div className="card">
      <h2>{title}</h2>
      <p>{content}</p>
    </div>
  );
};

Class Components (Legacy)#

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

JSX (JavaScript XML)#

JSX is a syntax extension for JavaScript that looks similar to HTML. It allows you to write HTML-like code in JavaScript:

Code
// JSX syntax
const element = (
  <div className="container">
    <h1>Hello, World!</h1>
    <p>This is JSX</p>
    <img src="image.jpg" alt="Description" />
  </div>
);

// JSX with expressions
const name = "John";
const element = <h1>Hello, {name}!</h1>;

// JSX with conditional rendering
const isLoggedIn = true;
const element = (
  <div>
    {isLoggedIn ? <p>Welcome back!</p> : <p>Please log in</p>}
    {isLoggedIn && <button>Logout</button>}
  </div>
);

// JSX with lists
const items = ["Apple", "Banana", "Orange"];
const list = (
  <ul>
    {items.map((item, index) => (
      <li key={index}>{item}</li>
    ))}
  </ul>
);

Props#

Props (properties) are read-only data passed from parent to child components:

Code
// Parent component
function App() {
  return (
    <div>
      <Welcome name="John" age={25} city="Moradabad" />
      <Welcome name="Jane" age={30} city="Delhi" />
    </div>
  );
}

// Child component receiving props
function Welcome(props) {
  return (
    <div>
      <h1>Hello, {props.name}!</h1>
      <p>Age: {props.age}, City: {props.city}</p>
    </div>
  );
}

// Using destructuring
function Welcome({ name, age, city }) {
  return (
    <div>
      <h1>Hello, {name}!</h1>
      <p>Age: {age}, City: {city}</p>
    </div>
  );
}

State#

State allows components to create and manage their own data. State changes trigger re-renders:

Code
import { useState } from 'react';

function Counter() {
  // useState returns [currentValue, setterFunction]
  const [count, setCount] = useState(0);
  
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>
      <button onClick={() => setCount(count - 1)}>
        Decrement
      </button>
      <button onClick={() => setCount(0)}>
        Reset
      </button>
    </div>
  );
}

// State with objects
function UserProfile() {
  const [user, setUser] = useState({
    name: "John",
    age: 25,
    email: "john@example.com"
  });
  
  const updateName = () => {
    setUser({ ...user, name: "Jane" });
  };
  
  return (
    <div>
      <p>Name: {user.name}</p>
      <button onClick={updateName}>Update Name</button>
    </div>
  );
}

React Hooks#

Hooks are functions that let you "hook into" React features. They start with "use":

useState Hook#

Code
import { useState } from 'react';

function Example() {
  const [state, setState] = useState(initialValue);
  // ...
}

useEffect Hook#

useEffect lets you perform side effects in functional components:

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

function Counter() {
  const [count, setCount] = useState(0);
  
  // Runs after every render
  useEffect(() => {
    document.title = `Count: ${count}`;
  });
  
  // Runs only on mount
  useEffect(() => {
    console.log("Component mounted");
  }, []);
  
  // Runs when count changes
  useEffect(() => {
    console.log("Count changed:", count);
  }, [count]);
  
  // Cleanup function
  useEffect(() => {
    const timer = setInterval(() => {
      setCount(c => c + 1);
    }, 1000);
    
    return () => clearInterval(timer); // Cleanup
  }, []);
  
  return <div>Count: {count}</div>;
}

Other Common Hooks#

Code
import { useState, useEffect, useContext, useRef, useMemo, useCallback } from 'react';

// useContext - access context
const theme = useContext(ThemeContext);

// useRef - access DOM or store mutable value
const inputRef = useRef(null);
inputRef.current.focus();

// useMemo - memoize expensive calculations
const expensiveValue = useMemo(() => {
  return computeExpensiveValue(a, b);
}, [a, b]);

// useCallback - memoize functions
const memoizedCallback = useCallback(() => {
  doSomething(a, b);
}, [a, b]);

Event Handling#

Code
function Form() {
  const [input, setInput] = useState("");
  
  // Event handler
  const handleSubmit = (e) => {
    e.preventDefault(); // Prevent form submission
    console.log("Form submitted:", input);
  };
  
  const handleChange = (e) => {
    setInput(e.target.value);
  };
  
  return (
    <form onSubmit={handleSubmit}>
      <input 
        type="text" 
        value={input}
        onChange={handleChange}
        placeholder="Enter text"
      />
      <button type="submit">Submit</button>
    </form>
  );
}

// Inline event handlers
function Button() {
  return (
    <button onClick={() => console.log("Clicked!")}>
        Click me
      </button>
  );
}

Conditional Rendering#

Code
function Greeting({ isLoggedIn }) {
  // Using if-else
  if (isLoggedIn) {
    return <h1>Welcome back!</h1>;
  } else {
    return <h1>Please log in</h1>;
  }
}

// Using ternary operator
function Message({ count }) {
  return (
    <div>
      {count > 0 ? (
        <p>You have {count} messages</p>
      ) : (
        <p>No messages</p>
      )}
    </div>
  );
}

// Using logical AND
function Notification({ hasNotification }) {
  return (
    <div>
      {hasNotification && <p>You have a new notification</p>}
    </div>
  );
}

Lists and Keys#

Code
function TodoList({ todos }) {
  return (
    <ul>
      {todos.map((todo) => (
        <li key={todo.id}>
          {todo.text}
        </li>
      ))}
    </ul>
  );
}

// Keys help React identify which items changed
// Use unique, stable IDs as keys, not array indices

Forms and Controlled Components#

Code
function LoginForm() {
  const [formData, setFormData] = useState({
    username: "",
    password: ""
  });
  
  const handleChange = (e) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value
    });
  };
  
  const handleSubmit = (e) => {
    e.preventDefault();
    console.log("Form data:", formData);
  };
  
  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        name="username"
        value={formData.username}
        onChange={handleChange}
        placeholder="Username"
      />
      <input
        type="password"
        name="password"
        value={formData.password}
        onChange={handleChange}
        placeholder="Password"
      />
      <button type="submit">Login</button>
    </form>
  );
}

Component Lifecycle#

In functional components, useEffect handles lifecycle events:

Code
function Component() {
  useEffect(() => {
    // ComponentDidMount equivalent
    console.log("Component mounted");
    
    return () => {
      // ComponentWillUnmount equivalent
      console.log("Component unmounted");
    };
  }, []);
  
  useEffect(() => {
    // ComponentDidUpdate equivalent
    console.log("Component updated");
  });
  
  return <div>Component</div>;
}

Best Practices#

  • Use functional components and hooks
  • Keep components small and focused
  • Use meaningful component and prop names
  • Extract reusable logic into custom hooks
  • Use keys properly in lists
  • Avoid direct state mutations
  • Use useEffect cleanup functions
  • Optimize with useMemo and useCallback when needed
  • Follow the single responsibility principle
  • Use PropTypes or TypeScript for type checking

Ready to test your knowledge?

Take the quiz to reinforce what you've learned in this article.

Start Quiz

Article discussion

(0)

Join the discussion — login to comment and help other developers.

Login to comment