reactjs
/

React Introduction – Getting Started with React

Last Sync: Today

On this page

16
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

reactjs

React Introduction – Getting Started with React

What is React?

React is a JavaScript library for building user interfaces, developed by Facebook. It allows you to create reusable UI components and manage application state efficiently. React uses a virtual DOM for optimal performance and supports both web and mobile platforms (React Native).

Why React?

  • Declarative – Describe how your UI should look, React handles updates
  • Component-Based – Build encapsulated components that manage their own state
  • Learn Once, Write Anywhere – React DOM for web, React Native for mobile
  • Huge Ecosystem – Rich libraries, tools, and community support
  • Performance – Virtual DOM for efficient updates

Setting Up a React Project

BASHRead-only
1
# Create a new React app with Vite (recommended)
npm create vite@latest my-app -- --template react
cd my-app
npm install
npm run dev

# Or with Create React App (legacy)
npx create-react-app my-app
cd my-app
npm start

# Or with Next.js (full-stack)
npx create-next-app@latest my-app

Your First Component

React JSXRead-only
1
// App.jsx
function App() {
  return (
    <div>
      <h1>Hello, React!</h1>
      <p>Welcome to your first React component.</p>
    </div>
  );
}

export default App;

JSX Explained

JSX (JavaScript XML) is a syntax extension that allows you to write HTML-like code in JavaScript. It gets compiled to regular JavaScript function calls.

React JSXRead-only
1
// JSX syntax
const element = <h1 className="title">Hello, {name}!</h1>;

// Compiled to
const element = React.createElement('h1', { className: 'title' }, 'Hello, ', name, '!');

// JSX rules:
// - Use camelCase for attributes (className, onClick)
// - Wrap multiple elements in fragments <>...</> or <div>...</div>
// - Embed JavaScript expressions with {}
// - Self-close tags like <img />

Components: Props

React JSXRead-only
1
// Child component
function Greeting({ name, age }) {
  return (
    <div>
      <h2>Hello, {name}!</h2>
      <p>Age: {age}</p>
    </div>
  );
}

// Parent component
function App() {
  return (
    <div>
      <Greeting name="Alice" age={25} />
      <Greeting name="Bob" age={30} />
    </div>
  );
}

// Default props
function Button({ label = 'Click me', onClick }) {
  return <button onClick={onClick}>{label}</button>;
}

Components: State (useState)

React JSXRead-only
1
import { useState } from 'react';

function Counter() {
  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>
    </div>
  );
}

// Multiple state variables
function UserForm() {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');

  return (
    <form>
      <input value={name} onChange={(e) => setName(e.target.value)} />
      <input value={email} onChange={(e) => setEmail(e.target.value)} />
    </form>
  );
}

useEffect – Side Effects

React JSXRead-only
1
import { useState, useEffect } from 'react';

function DataFetcher() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // Runs after component mounts
    fetch('https://api.example.com/data')
      .then(res => res.json())
      .then(data => {
        setData(data);
        setLoading(false);
      });

    // Optional cleanup function
    return () => {
      // Cleanup subscriptions, timers, etc.
      console.log('Component unmounted');
    };
  }, []); // Empty array = run once

  if (loading) return <p>Loading...</p>;
  return <div>{JSON.stringify(data)}</div>;
}

Event Handling

React JSXRead-only
1
function EventDemo() {
  const handleClick = (event) => {
    console.log('Button clicked!', event);
  };

  const handleInputChange = (e) => {
    console.log('Input value:', e.target.value);
  };

  const handleFormSubmit = (e) => {
    e.preventDefault();
    console.log('Form submitted!');
  };

  return (
    <div>
      <button onClick={handleClick}>Click Me</button>
      <input onChange={handleInputChange} placeholder="Type something..." />
      <form onSubmit={handleFormSubmit}>
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

Conditional Rendering

React JSXRead-only
1
function ConditionalDemo({ isLoggedIn, user }) {
  // If-else
  if (isLoggedIn) {
    return <h1>Welcome back, {user.name}!</h1>;
  }
  return <h1>Please log in</h1>;

  // Ternary operator
  return (
    <div>
      {isLoggedIn ? (
        <Dashboard user={user} />
      ) : (
        <LoginForm />
      )}
    </div>
  );

  // Logical && operator
  return (
    <div>
      {isLoggedIn && <WelcomeMessage />}
      {!isLoggedIn && <LoginPrompt />}
    </div>
  );
}

Rendering Lists

React JSXRead-only
1
function TodoList({ todos }) {
  return (
    <ul>
      {todos.map(todo => (
        <li key={todo.id}>
          <input type="checkbox" checked={todo.completed} readOnly />
          {todo.text}
        </li>
      ))}
    </ul>
  );
}

// Filtered list
function FilteredList({ items, filterText }) {
  const filtered = items.filter(item =>
    item.name.toLowerCase().includes(filterText.toLowerCase())
  );

  return (
    <ul>
      {filtered.map(item => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
}

React Hooks Overview

HookPurposeExample
useStateLocal state managementconst [count, setCount] = useState(0)
useEffectSide effectsuseEffect(() => {}, [])
useContextAccess contextconst theme = useContext(ThemeContext)
useReducerComplex state logicconst [state, dispatch] = useReducer(reducer, initialState)
useCallbackMemoized functionsconst memoized = useCallback(() => {}, [deps])
useMemoMemoized valuesconst memoized = useMemo(() => compute(), [deps])
useRefMutable referencesconst inputRef = useRef(null)

Component Communication

React JSXRead-only
1
// Parent to Child via props
function Parent() {
  const message = "Hello from parent";
  return <Child message={message} />;
}

function Child({ message }) {
  return <p>{message}</p>;
}

// Child to Parent via callbacks
function Parent() {
  const handleChildClick = (data) => {
    console.log('Data from child:', data);
  };
  return <Child onAction={handleChildClick} />;
}

function Child({ onAction }) {
  return (
    <button onClick={() => onAction('Child data')}>
      Send to Parent
    </button>
  );
}

// Sibling communication via shared parent
function Siblings() {
  const [sharedState, setSharedState] = useState('');
  return (
    <div>
      <SiblingA setSharedState={setSharedState} />
      <SiblingB sharedState={sharedState} />
    </div>
  );
}

Best Practices

  • Use functional components and hooks – Avoid class components in new code
  • Keep components small and focused – Single responsibility principle
  • Use meaningful names – Components, props, and state should be descriptive
  • Lift state up – Share state by moving it to common ancestors
  • Avoid direct state mutation – Always use setState functions
  • Use keys in lists – Stable, unique, predictable IDs
  • Memoize expensive computations – useMemo and useCallback
  • Use React DevTools – Debug and profile your components

Common Mistakes

  • Mutating state directly – state.count++ instead of setState({...state, count: state.count + 1})
  • Calling hooks conditionally – Hooks must be called at the top level
  • Missing dependency arrays – Causes stale closures and infinite loops
  • Using index as key – Causes issues with reordering
  • Forgetting to prevent default – Form submissions cause page reloads

Conclusion

React provides a powerful, component-based approach to building user interfaces. Start with components, props, and state, then gradually explore hooks, context, and advanced patterns. Practice building small apps to reinforce these concepts.

Try it yourself

import { useState } from 'react';

function TodoApp() {
  const [todos, setTodos] = useState([]);
  const [input, setInput] = useState('');

  const addTodo = () => {
    if (input.trim()) {
      setTodos([...todos, { id: Date.now(), text: input, completed: false }]);
      setInput('');
    }
  };

  const toggleTodo = (id) => {
    setTodos(todos.map(todo =>
      todo.id === id ? { ...todo, completed: !todo.completed } : todo
    ));
  };

  return (
    <div>
      <h1>Todo List</h1>
      <div>
        <input
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyPress={(e) => e.key === 'Enter' && addTodo()}
          placeholder="Add a new todo..."
        />
        <button onClick={addTodo}>Add</button>
      </div>
      <ul>
        {todos.map(todo => (
          <li key={todo.id}>
            <input
              type="checkbox"
              checked={todo.completed}
              onChange={() => toggleTodo(todo.id)}
            />
            <span style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}>
              {todo.text}
            </span>
          </li>
        ))}
      </ul>
      <p>{todos.length} todo(s) remaining</p>
    </div>
  );
}

export default TodoApp;

Test Your Knowledge

Q1
of 4

What is the correct way to create state in React?

A
this.state = {}
B
createState()
C
useState()
D
state()
Q2
of 4

What is JSX?

A
JavaScript XML
B
Java Syntax Extension
C
JSON XHR
D
JavaScript XHR
Q3
of 4

Which hook is used for side effects?

A
useState
B
useContext
C
useEffect
D
useReducer
Q4
of 4

How do you pass data from parent to child?

A
State
B
Props
C
Hooks
D
Context

Frequently Asked Questions

What is React?

A JavaScript library for building user interfaces with reusable components.

What is JSX?

JavaScript syntax extension that allows HTML-like code in JavaScript.

What are React Hooks?

Functions that let you use state and other React features in functional components.

React vs React DOM?

React is the core library; React DOM provides DOM-specific methods for web apps.

Next

react setup

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.