Skip to main content
Sproutern LogoSproutern
InterviewsGamesBlogToolsAbout
Sproutern LogoSproutern
Donate
Sproutern LogoSproutern

Your complete education and career platform. Access real interview experiences, free tools, and comprehensive resources to succeed in your professional journey.

Company

About UsContact UsSuccess StoriesHire Me / ServicesOur MethodologyBlog❤️ Donate

For Students

Find InternshipsScholarshipsCompany ReviewsCareer ToolsFree ResourcesCollege PlacementsSalary Guide

🌍 Study Abroad

Country Guides🇩🇪 Study in Germany🇺🇸 Study in USA🇬🇧 Study in UK🇨🇦 Study in CanadaGPA Converter

Resources

Resume TemplatesCover Letter SamplesInterview Cheat SheetLinkedIn OptimizationSalary NegotiationGitHub Profile GuideATS Resume KeywordsResume CheckerCGPA ConverterIT CertificationsDSA RoadmapInterview QuestionsFAQ

Legal

Privacy PolicyTerms & ConditionsCookie PolicyDisclaimerSitemap Support

© 2026 Sproutern. All rights reserved.

•

Made with ❤️ for students worldwide

Follow Us:
    Explore More
    🛠️Free Career Tools💼Interview Experiences🗺️Career Roadmaps
    Keep reading

    Move from advice to action

    Use supporting tools and destination pages to turn an article into a concrete next step.

    Interview Prep Hub

    Prep

    Practice frameworks, question banks, and checklists in one place.

    Open page

    Resume Score Checker

    Tool

    Test whether your resume matches the role you want.

    Open page

    Company Guides

    Research

    Review hiring patterns, salary ranges, and work culture.

    Open page

    Interview Experiences

    Stories

    Read real candidate stories before your next round.

    Open page
    Popular with students
    CGPA ConverterSalary CalculatorResume Score CheckerInterview Prep HubStudy in USA Guide
    Article review
    Human reviewed
    Source-backed

    How Sproutern reviews career articles

    Our blog is written for students, freshers, and early-career professionals. We aim for useful, readable guidance first, but we still expect articles to cite primary regulations, university guidance, or employer-side evidence wherever the advice depends on facts rather than opinion.

    Written by

    Premkumar M

    Founder, editor, and product lead at Sproutern

    View author profile

    Reviewed by

    Sproutern Editorial Team

    Career editors and quality reviewers working from our public editorial policy

    Review standards

    Last reviewed

    March 6, 2026

    Freshness checks are recorded on pages where the update is material to the reader.

    Update cadence

    Evergreen articles are reviewed at least quarterly; time-sensitive posts move sooner

    Time-sensitive topics move faster when rules, deadlines, or market signals change.

    How this content is built and maintained

    We publish articles only after checking whether the advice depends on a policy, a market signal, or first-hand experience. If a section depends on an official rule, we look for the original source. If it depends on experience, we label it as practical guidance instead of hard fact.

    • We do not treat AI-generated drafts as final content; human editors review and rewrite before publication.
    • If an article cites a hiring trend or academic rule, the editorial team looks for the original report, regulation, or handbook first.
    • Major updates are logged so readers can see whether a change reflects a new policy, fresher data, or a corrected explanation.
    Read our methodologyEditorial guidelinesReport a correction

    Primary sources and expert references

    Not every article uses the same dataset, but the editorial expectation is consistent: cite the primary rule, employer guidance, or research owner wherever it materially affects the reader.

    • Primary regulations, employer documentation, and university sources

      Blog articles are expected to cite the original policy, handbook, or employer guidance before we publish practical takeaways.

    • OECD and World Economic Forum

      Used for labor-market, education, and future-of-work context when broader data is needed.

    • NACE and public recruiter guidance

      Used for resume, interview, internship, and early-career hiring patterns where employer-side evidence matters.

    Recent updates

    March 6, 2026

    Added reviewer and methodology disclosure to major blog surfaces

    The blog section now clearly shows review context, source expectations, and correction workflow alongside major article experiences.

    Reader feedback loop

    Writers and editors monitor feedback for factual issues, unclear advice, and stale references that should be refreshed.

    Prefer the full policy pages? Read our public standards or contact the team if a major page needs a correction.Open standards
    Back to Blog
    Loading TOC...
    Programming

    React.js Tutorial for Beginners: Complete Guide

    Sproutern Career TeamLast Updated: 2026-01-0626 min read
    Reviewed by Sproutern Editorial TeamEditorial standardsMethodology

    Learn React.js from scratch with this comprehensive beginner's guide. Covers components, state, props, hooks, and building your first React application step by step.

    React.js Tutorial for Beginners: Complete Guide

    React.js has become the most popular JavaScript library for building user interfaces. Created by Facebook, it powers Instagram, WhatsApp Web, Netflix, and thousands of other applications.

    If you're looking to enter front-end development or level up your JavaScript skills, learning React is one of the best investments you can make. This comprehensive tutorial takes you from zero to building real React applications.


    What is React?

    Definition

    React is a JavaScript library for building user interfaces, specifically for single-page applications. It allows you to create reusable UI components that update efficiently when data changes.

    React vs Other Frameworks

    FeatureReactVueAngular
    TypeLibraryFrameworkFramework
    Learning CurveMediumEasySteep
    SizeSmall (42kb)Small (33kb)Large (143kb)
    Data BindingOne-wayTwo-wayTwo-way
    Created ByFacebookEvan YouGoogle
    PopularityHighestHighHigh

    Why Learn React?

    ReasonExplanation
    Job MarketMost in-demand front-end skill
    Large EcosystemHuge community, many libraries
    Component-BasedReusable, maintainable code
    React NativeBuild mobile apps with same skills
    PerformanceVirtual DOM makes updates efficient
    Industry StandardUsed by top companies globally

    Prerequisites

    Before starting React, you should know:

    SkillLevel Needed
    HTMLComfortable
    CSSComfortable
    JavaScriptStrong fundamentals

    JavaScript Concepts You Need:

    ConceptWhy Important
    Variables (let, const)Used throughout
    Arrow functionsComponent syntax
    Array methods (map, filter)Rendering lists
    DestructuringProps and state
    Spread operatorUpdating state
    Modules (import/export)Organizing code
    Template literalsJSX usage
    Promises/async-awaitAPI calls

    If these are unfamiliar, spend 1-2 weeks on modern JavaScript first.


    Setting Up Your Development Environment

    Requirements

    1. Node.js (version 16+)

      • Download from nodejs.org
      • Verify: node --version
    2. Code Editor

      • VS Code (recommended)
      • Extensions: ES7+ React snippets, Prettier
    3. Browser

      • Chrome with React Developer Tools extension

    Creating Your First React App

    Using Create React App (CRA):

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

    Using Vite (Faster alternative):

    npm create vite@latest my-app -- --template react
    cd my-app
    npm install
    npm run dev
    

    Your app runs at http://localhost:3000 (CRA) or http://localhost:5173 (Vite).

    Project Structure

    my-app/
    ├── node_modules/     # Dependencies
    ├── public/           # Static files
    │   └── index.html    # Main HTML file
    ├── src/              # Source code
    │   ├── App.js        # Main component
    │   ├── App.css       # Styles
    │   ├── index.js      # Entry point
    │   └── index.css     # Global styles
    ├── package.json      # Project config
    └── README.md
    

    Understanding JSX

    What is JSX?

    JSX (JavaScript XML) lets you write HTML-like code in JavaScript. It's not HTML—it's a syntax extension that gets compiled to JavaScript.

    JSX:

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

    Compiles to:

    const element = React.createElement('h1', null, 'Hello, World!');
    

    JSX Rules

    RuleExample
    Return single root elementWrap in <div> or <> (Fragment)
    Close all tags<img /> not <img>
    Use className not class<div className="box">
    Use htmlFor not for<label htmlFor="name">
    camelCase for attributesonClick, onSubmit
    JavaScript in {}<p>{variable}</p>

    JSX Examples

    Expressions in JSX:

    const name = 'John';
    const element = <h1>Hello, {name}!</h1>;
    

    Conditional Rendering:

    const isLoggedIn = true;
    
    return <div>{isLoggedIn ? <p>Welcome back!</p> : <p>Please log in</p>}</div>;
    

    Rendering Lists:

    const items = ['Apple', 'Banana', 'Orange'];
    
    return (
      <ul>
        {items.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    );
    

    Components

    What are Components?

    Components are the building blocks of React applications. They are reusable, independent pieces of UI.

    Types of Components:

    TypeSyntaxState Support
    Function ComponentFunctionYes (with hooks)
    Class ComponentES6 ClassYes (built-in)

    Modern React uses function components almost exclusively.

    Creating a Function Component

    Basic Component:

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

    Arrow Function:

    const Welcome = () => {
      return <h1>Hello, World!</h1>;
    };
    

    Using the Component:

    function App() {
      return (
        <div>
          <Welcome />
          <Welcome />
        </div>
      );
    }
    

    Component Best Practices

    PracticeWhy
    One component per fileOrganization
    PascalCase namingReact requirement
    Start simpleBreak down later
    Keep components smallEasier to maintain
    Single responsibilityOne purpose per component

    Example: Breaking Down UI

    Full Page:

    function App() {
      return (
        <div>
          <Header />
          <MainContent />
          <Footer />
        </div>
      );
    }
    

    Header Component:

    function Header() {
      return (
        <header>
          <Logo />
          <Navigation />
        </header>
      );
    }
    

    Props

    What are Props?

    Props (properties) are how you pass data from parent to child components. They're read-only—a component cannot modify its own props.

    Passing Props

    Parent Component:

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

    Child Component:

    function Greeting(props) {
      return (
        <p>
          Hello, {props.name}! You are {props.age} years old.
        </p>
      );
    }
    

    Destructuring Props

    Cleaner Syntax:

    function Greeting({ name, age }) {
      return (
        <p>
          Hello, {name}! You are {age} years old.
        </p>
      );
    }
    

    Default Props

    function Greeting({ name = 'Guest', age = 0 }) {
      return (
        <p>
          Hello, {name}! You are {age} years old.
        </p>
      );
    }
    

    Props with Children

    Special children prop for content inside component tags:

    function Card({ children, title }) {
      return (
        <div className="card">
          <h2>{title}</h2>
          {children}
        </div>
      );
    }
    
    // Usage
    <Card title="Welcome">
      <p>This is the card content</p>
      <button>Click me</button>
    </Card>;
    

    State with useState Hook

    What is State?

    State is data that can change over time and affects what the component renders. When state changes, React re-renders the component.

    useState Hook

    import { useState } from 'react';
    
    function Counter() {
      const [count, setCount] = useState(0);
    
      return (
        <div>
          <p>Count: {count}</p>
          <button onClick={() => setCount(count + 1)}>Increment</button>
        </div>
      );
    }
    

    Breakdown:

    • useState(0): Initialize state with value 0
    • count: Current state value
    • setCount: Function to update state
    • Never modify state directly, always use setter

    Updating State

    With New Value:

    setCount(5); // Set to 5
    

    With Previous Value (recommended for updates based on previous):

    setCount((prevCount) => prevCount + 1);
    

    Multiple State Variables

    function Form() {
      const [name, setName] = useState('');
      const [email, setEmail] = useState('');
      const [age, setAge] = useState(0);
    
      // ...
    }
    

    State with Objects

    function Form() {
      const [formData, setFormData] = useState({
        name: '',
        email: '',
        age: 0,
      });
    
      const handleChange = (e) => {
        setFormData({
          ...formData, // Keep existing values
          [e.target.name]: e.target.value, // Update one field
        });
      };
    
      return (
        <input
          name="name"
          value={formData.name}
          onChange={handleChange}
        />
      );
    }
    

    State with Arrays

    function TodoList() {
      const [todos, setTodos] = useState(['Learn React', 'Build a project']);
    
      const addTodo = (newTodo) => {
        setTodos([...todos, newTodo]); // Add to end
      };
    
      const removeTodo = (index) => {
        setTodos(todos.filter((_, i) => i !== index)); // Remove by index
      };
    
      return (
        <ul>
          {todos.map((todo, index) => (
            <li key={index}>
              {todo}
              <button onClick={() => removeTodo(index)}>Delete</button>
            </li>
          ))}
        </ul>
      );
    }
    

    Event Handling

    Basic Events

    function Button() {
      const handleClick = () => {
        alert('Button clicked!');
      };
    
      return <button onClick={handleClick}>Click Me</button>;
    }
    

    Inline Handler (for simple cases):

    <button onClick={() => alert('Clicked!')}>Click</button>
    

    Common Events

    EventReact EventUse Case
    ClickonClickButtons, links
    ChangeonChangeInputs, selects
    SubmitonSubmitForms
    FocusonFocusInput focus
    BluronBlurInput loses focus
    Mouse OveronMouseOverHover effects
    Key PressonKeyDownKeyboard shortcuts

    Passing Arguments to Event Handlers

    function ItemList() {
      const handleDelete = (id) => {
        console.log('Deleting item:', id);
      };
    
      return <button onClick={() => handleDelete(5)}>Delete Item 5</button>;
    }
    

    Form Handling

    function LoginForm() {
      const [formData, setFormData] = useState({
        email: '',
        password: '',
      });
    
      const handleChange = (e) => {
        const { name, value } = e.target;
        setFormData((prev) => ({
          ...prev,
          [name]: value,
        }));
      };
    
      const handleSubmit = (e) => {
        e.preventDefault(); // Prevent page reload
        console.log('Form submitted:', formData);
      };
    
      return (
        <form onSubmit={handleSubmit}>
          <input
            type="email"
            name="email"
            value={formData.email}
            onChange={handleChange}
            placeholder="Email"
          />
          <input
            type="password"
            name="password"
            value={formData.password}
            onChange={handleChange}
            placeholder="Password"
          />
          <button type="submit">Login</button>
        </form>
      );
    }
    

    useEffect Hook

    What is useEffect?

    useEffect lets you perform side effects in function components:

    • Fetching data
    • Setting up subscriptions
    • Manually changing the DOM
    • Timers

    Basic useEffect

    import { useState, useEffect } from 'react';
    
    function Example() {
      const [count, setCount] = useState(0);
    
      useEffect(() => {
        // Runs after every render
        document.title = `Count: ${count}`;
      });
    
      return (
        <div>
          <p>Count: {count}</p>
          <button onClick={() => setCount(count + 1)}>Increment</button>
        </div>
      );
    }
    

    Dependency Array

    DependencyWhen Effect Runs
    No arrayAfter every render
    Empty array []Only on mount (once)
    With values [value]When value changes

    Run Once on Mount:

    useEffect(() => {
      console.log('Component mounted');
    }, []); // Empty array
    

    Run When Value Changes:

    useEffect(() => {
      console.log('Count changed to:', count);
    }, [count]); // Only when count changes
    

    Cleanup Function

    For effects that need cleanup (subscriptions, timers):

    useEffect(() => {
      const timer = setInterval(() => {
        console.log('Tick');
      }, 1000);
    
      // Cleanup function
      return () => {
        clearInterval(timer);
      };
    }, []);
    

    Fetching Data

    function UserProfile({ userId }) {
      const [user, setUser] = useState(null);
      const [loading, setLoading] = useState(true);
    
      useEffect(() => {
        const fetchUser = async () => {
          try {
            const response = await fetch(`/api/users/${userId}`);
            const data = await response.json();
            setUser(data);
          } catch (error) {
            console.error('Error fetching user:', error);
          } finally {
            setLoading(false);
          }
        };
    
        fetchUser();
      }, [userId]); // Re-fetch when userId changes
    
      if (loading) return <p>Loading...</p>;
      if (!user) return <p>User not found</p>;
    
      return <div>{user.name}</div>;
    }
    

    Conditional Rendering

    If Statement (Outside JSX)

    function Greeting({ isLoggedIn }) {
      if (isLoggedIn) {
        return <h1>Welcome back!</h1>;
      }
      return <h1>Please sign in</h1>;
    }
    

    Ternary Operator

    function Greeting({ isLoggedIn }) {
      return <div>{isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in</h1>}</div>;
    }
    

    Logical AND (&&)

    Render something only if condition is true:

    function Notification({ hasMessages, count }) {
      return <div>{hasMessages && <p>You have {count} new messages</p>}</div>;
    }
    

    Multiple Conditions

    function StatusMessage({ status }) {
      return (
        <div>
          {status === 'loading' && <Spinner />}
          {status === 'error' && <ErrorMessage />}
          {status === 'success' && <SuccessMessage />}
        </div>
      );
    }
    

    Lists and Keys

    Rendering Lists

    function TodoList() {
      const todos = [
        { id: 1, text: 'Learn React' },
        { id: 2, text: 'Build a project' },
        { id: 3, text: 'Deploy it' },
      ];
    
      return (
        <ul>
          {todos.map((todo) => (
            <li key={todo.id}>{todo.text}</li>
          ))}
        </ul>
      );
    }
    

    Why Keys Matter

    Keys help React identify which items changed, were added, or removed:

    • Use unique, stable identifiers
    • Don't use array index if items can reorder
    • Keys must be unique among siblings

    Good Key:

    {
      todos.map((todo) => <li key={todo.id}>{todo.text}</li>);
    }
    

    Bad Key (avoid):

    {
      todos.map((todo, index) => (
        <li key={index}>{todo.text}</li> // Problematic if list reorders
      ));
    }
    

    Styling in React

    Option 1: CSS Stylesheets

    App.css:

    .button {
      background-color: blue;
      color: white;
      padding: 10px 20px;
    }
    

    Component:

    import './App.css';
    
    function Button() {
      return <button className="button">Click Me</button>;
    }
    

    Option 2: Inline Styles

    function Button() {
      const buttonStyle = {
        backgroundColor: 'blue',
        color: 'white',
        padding: '10px 20px',
        border: 'none',
        borderRadius: '5px',
      };
    
      return <button style={buttonStyle}>Click Me</button>;
    }
    

    Option 3: CSS Modules

    Button.module.css:

    .button {
      background-color: blue;
      color: white;
    }
    

    Component:

    import styles from './Button.module.css';
    
    function Button() {
      return <button className={styles.button}>Click Me</button>;
    }
    

    Option 4: Styled Components

    import styled from 'styled-components';
    
    const StyledButton = styled.button`
      background-color: blue;
      color: white;
      padding: 10px 20px;
    
      &:hover {
        background-color: darkblue;
      }
    `;
    
    function Button() {
      return <StyledButton>Click Me</StyledButton>;
    }
    

    Building a Complete Project: Todo App

    Let's build a complete todo application:

    App.js

    import { useState } from 'react';
    import TodoForm from './components/TodoForm';
    import TodoList from './components/TodoList';
    import './App.css';
    
    function App() {
      const [todos, setTodos] = useState([]);
    
      const addTodo = (text) => {
        const newTodo = {
          id: Date.now(),
          text,
          completed: false,
        };
        setTodos([...todos, newTodo]);
      };
    
      const toggleTodo = (id) => {
        setTodos(
          todos.map((todo) => (todo.id === id ? { ...todo, completed: !todo.completed } : todo)),
        );
      };
    
      const deleteTodo = (id) => {
        setTodos(todos.filter((todo) => todo.id !== id));
      };
    
      return (
        <div className="app">
          <h1>Todo App</h1>
          <TodoForm onAdd={addTodo} />
          <TodoList
            todos={todos}
            onToggle={toggleTodo}
            onDelete={deleteTodo}
          />
        </div>
      );
    }
    
    export default App;
    

    TodoForm.js

    import { useState } from 'react';
    
    function TodoForm({ onAdd }) {
      const [input, setInput] = useState('');
    
      const handleSubmit = (e) => {
        e.preventDefault();
        if (input.trim()) {
          onAdd(input);
          setInput('');
        }
      };
    
      return (
        <form onSubmit={handleSubmit}>
          <input
            type="text"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            placeholder="Add a new todo..."
          />
          <button type="submit">Add</button>
        </form>
      );
    }
    
    export default TodoForm;
    

    TodoList.js

    import TodoItem from './TodoItem';
    
    function TodoList({ todos, onToggle, onDelete }) {
      if (todos.length === 0) {
        return <p>No todos yet. Add one above!</p>;
      }
    
      return (
        <ul className="todo-list">
          {todos.map((todo) => (
            <TodoItem
              key={todo.id}
              todo={todo}
              onToggle={onToggle}
              onDelete={onDelete}
            />
          ))}
        </ul>
      );
    }
    
    export default TodoList;
    

    TodoItem.js

    function TodoItem({ todo, onToggle, onDelete }) {
      return (
        <li className={`todo-item ${todo.completed ? 'completed' : ''}`}>
          <input
            type="checkbox"
            checked={todo.completed}
            onChange={() => onToggle(todo.id)}
          />
          <span>{todo.text}</span>
          <button onClick={() => onDelete(todo.id)}>Delete</button>
        </li>
      );
    }
    
    export default TodoItem;
    

    Next Steps After Basics

    What to Learn Next

    TopicWhy Important
    React RouterMulti-page apps
    Context APIGlobal state
    Custom HooksReusable logic
    State Management (Redux/Zustand)Complex state
    React QueryServer state
    TypeScript with ReactType safety
    Testing (Jest, React Testing Library)Quality assurance

    Project Ideas for Practice

    LevelProject
    BeginnerTodo App, Counter, Quiz App
    IntermediateWeather App, E-commerce Cart, Blog
    AdvancedSocial Media Clone, Dashboard, Full-stack App

    Key Takeaways

    1. React uses components—reusable UI building blocks
    2. JSX mixes HTML and JavaScript—with some syntax differences
    3. Props pass data down—parent to child, read-only
    4. State is for changing data—triggers re-renders
    5. Hooks add functionality—useState, useEffect, and more
    6. Events use camelCase—onClick, onChange
    7. Keys identify list items—use unique IDs
    8. useEffect handles side effects—API calls, subscriptions
    9. Start simple, build up—don't over-engineer early
    10. Practice with projects—real apps teach more than tutorials

    Frequently Asked Questions

    How long does it take to learn React?

    Basics: 2-4 weeks. Comfortable for projects: 2-3 months. Advanced: 6+ months of building projects.

    Should I learn JavaScript first?

    Yes. Solid JavaScript fundamentals (especially ES6+) are essential. Spend 1-2 months on JavaScript before React.

    React vs Vue vs Angular—which to learn?

    React has the largest job market. Vue is easiest to learn. Angular is comprehensive but complex. For careers, React is usually the best choice.

    Do I need to learn class components?

    Not for new projects. Modern React uses function components with hooks. Learn them briefly for reading legacy code.

    What backend should I use with React?

    Any backend works. Popular choices: Node.js/Express, Python/Django, or Firebase for quick setup.


    Learning web development? Explore more resources on Sproutern for programming tutorials, career guidance, and skill development.


    Related Resources on Sproutern

    • AI Resume Optimizer — Get your resume reviewed by AI for free
    • Career Roadmaps — Plan your career path step by step
    • Interview Experiences — Read real stories from candidates
    • Salary Calculator — Compare salaries across companies
    • Typing Speed Test — Test and improve your typing speed

    This article was last reviewed and updated on February 23, 2026. Source: Sproutern Career Research Team.


    Related Resources on Sproutern

    • AI Resume Optimizer
    • Salary Calculator
    • Mock Interview Tool
    • LinkedIn Optimization Guide
    • Salary Negotiation Guide
    S

    Sproutern Career Team

    Our team of career experts, industry professionals, and former recruiters brings decades of combined experience in helping students and freshers launch successful careers.

    Free Resource

    🎯 Free Career Resource Pack

    Get 50+ real interview questions from top MNCs, ATS-optimized resume templates, and a step-by-step placement checklist — delivered to your inbox.

    🔒 No spam. We respect your privacy.

    Share:💬📨🐦💼

    Was this guide helpful?

    Related Articles

    Best Programming Languages to Learn

    Discover the best programming languages to learn for career growth and high-paying tech jobs....

    15 min read

    Data Structures and Algorithms: Complete Roadmap

    Master Data Structures and Algorithms with this complete roadmap. From arrays to dynamic programming...

    25 min read

    Cite This Article

    If you found this article helpful, please cite it as:

    Sproutern Team. "React.js Tutorial for Beginners: Complete Guide." Sproutern, 2026-01-06, https://app.sproutern.com/blog/reactjs-tutorial-beginners-complete-guide. Accessed April 10, 2026.