REACT JS

Build powerful user interfaces with React using reusable
components, props, state, and hooks.

React.js - JavaScript Library for Building User Interfaces

1. What is React?

React is a JavaScript library developed by Facebook for building fast and interactive user interfaces for web and mobile applications. It uses a component-based architecture and the virtual DOM.

2. Setting Up React

Install React using Create React App (CRA):

npx create-react-app my-app
cd my-app
npm start
3. JSX (JavaScript XML)

JSX allows you to write HTML in JavaScript. It looks like HTML but compiles to React.createElement calls.

const element = <h1>Hello, React!</h1>;
4. Functional Components

A functional component is a simple JavaScript function that returns JSX.

function Welcome() {
  return <h1>Welcome to React</h1>;
}
5. Class Components

Class-based components include lifecycle methods and state (before Hooks).

class Welcome extends React.Component {
  render() {
    return <h1>Hello from Class</h1>;
  }
}
6. Props (Properties)

Props are used to pass data from parent to child components.

function Greet(props) {
  return <h2>Hello, {props.name}!</h2>;
}
7. State

State is local data storage specific to a component.

import React, { useState } from 'react';
function Counter() {
  const [count, setCount] = useState(0);
  return (<button onClick={() => setCount(count + 1)}>{count}</button>);
}
8. Handling Events

React uses camelCase for event names and passes functions as event handlers.

<button onClick={handleClick}>Click Me</button>
9. Conditional Rendering

You can use if statements or ternary expressions to render elements conditionally.

{isLoggedIn ? <Logout /> : <Login />}
10. Lists and Keys

Use the map() function to render lists and assign a unique "key" to each element.

const items = ['A', 'B', 'C'];
const list = items.map((item, i) => <li key={i}>{item}</li>);

React - Advanced Concepts and Hooks

11. useEffect Hook

Performs side effects in functional components (e.g., data fetching, event listeners).

import React, { useEffect } from 'react';
useEffect(() => {
  console.log('Component Mounted');
}, []); // Empty array = run once
12. useContext Hook

Provides a way to share data (like theme or user data) without passing props manually.

const MyContext = React.createContext();
function Component() {
  const value = useContext(MyContext);
  return <p>{value}</p>;
}
13. useRef Hook

Creates a reference to a DOM element or to persist values across renders.

const inputRef = useRef();
useEffect(() => {
  inputRef.current.focus();
}, []);
14. useMemo Hook

Memosize expensive calculations and avoid unnecessary recalculations.

const result = useMemo(() => expensiveFn(data), [data]);
15. useCallback Hook

Returns a memoized version of a callback function to prevent unnecessary re-renders.

const handleClick = useCallback(() => {
  console.log("Clicked");
}, []);
16. React Forms

Use controlled components to handle form inputs.

const [name, setName] = useState('');
<input value={name} onChange={e => setName(e.target.value)} />
17. React Router (Routing)

Used for client-side routing between components/pages.

import { BrowserRouter, Routes, Route } from 'react-router-dom';
<BrowserRouter>
  <Routes>
    <Route path="/" element={} />
    <Route path="/about" element={} />
  </Routes>
</BrowserRouter>
18. React Lifecycle Methods (Class Components)

Methods like componentDidMount, componentDidUpdate, and componentWillUnmount are used to handle side effects.

componentDidMount() {
  console.log("Component mounted");
}
19. Lifting State Up

Move state to the closest common ancestor of components that need it.

Used when multiple components need access to shared state.

20. Conditional Styling

Apply styles dynamically using inline styles or class names.

<div style={{ color: isActive ? 'green' : 'red' }}>Status</div>
<div className={isActive ? 'active' : 'inactive'}>Status</div>

React – State Management, Performance & Testing

21. Context API (createContext & Provider)

Context lets you pass data through the component tree without drilling props.

// ThemeContext.js import { createContext } from 'react'; export const ThemeContext = createContext('light'); // App.jsx import React, { useContext } from 'react'; import { ThemeContext } from './ThemeContext'; function Toolbar() { const theme = useContext(ThemeContext); return <button className={`btn ${theme}`}>Theme Button</button>; } export default function App() { return ( <ThemeContext.Provider value="dark"> <Toolbar /> </ThemeContext.Provider> ); }
22. Redux Basics (Store + Provider)

Redux stores global state in a single store and updates it via actions and reducers.

/* store.js */ import { configureStore, createSlice } from '@reduxjs/toolkit'; const counterSlice = createSlice({ name: 'counter', initialState: { value: 0 }, reducers: { increment: state => { state.value += 1 } } }); export const { increment } = counterSlice.actions; export const store = configureStore({ reducer: counterSlice.reducer }); /* App.jsx */ import React from 'react'; import { Provider, useSelector, useDispatch } from 'react-redux'; import { store, increment } from './store'; function Counter() { const value = useSelector(state => state.value); const dispatch = useDispatch(); return ( <button onClick={() => dispatch(increment())}> Count: {value} </button> ); } export default function App() { return ( <Provider store={store}> <Counter /> </Provider> ); }
23. useReducer Hook

Good for complex state logic that involves multiple sub‑values.

import React, { useReducer } from 'react'; function reducer(state, action) { switch (action.type) { case 'add': return [...state, action.payload]; case 'remove': return state.filter((_, i) => i !== action.index); default: return state; } } export default function TodoList() { const [todos, dispatch] = useReducer(reducer, []); return ( <> <button onClick={() => dispatch({ type: 'add', payload: 'Learn React' })}> Add Todo </button> <ul> {todos.map((t, i) => ( <li key={i} onClick={() => dispatch({ type: 'remove', index: i })}>{t}</li> ))} </ul> </> ); }
24. Code Splitting with React.lazy & Suspense

Dynamically load components to reduce bundle size.

import React, { Suspense, lazy } from 'react'; const Chart = lazy(() => import('./Chart')); export default function App() { return ( <Suspense fallback={<div>Loading...</div>}> <Chart /> </Suspense> ); }
25. Error Boundary

Catches JavaScript errors anywhere in the child component tree.

import React from 'react'; class ErrorBoundary extends React.Component { state = { hasError: false }; static getDerivedStateFromError() { return { hasError: true }; } componentDidCatch(err, info) { console.error(err, info); } render() { return this.state.hasError ? <h2>Something went wrong</h2> : this.props.children; } } export default function App() { return ( <ErrorBoundary> <BuggyComponent /> </ErrorBoundary> ); }
26. PropTypes for Type‑Checking

Validate props to catch errors during development.

import PropTypes from 'prop-types'; function Hello({ name }) { return <h3>Hi {name}</h3>; } Hello.propTypes = { name: PropTypes.string.isRequired };
27. Custom Hooks

Reuse stateful logic across components.

import { useState, useEffect } from 'react'; export function useFetch(url) { const [data, setData] = useState(null); useEffect(() => { fetch(url).then(r => r.json()).then(setData); }, [url]); return data; } /* Usage */ const users = useFetch('https://jsonplaceholder.typicode.com/users');
28. React.memo

Prevents unnecessary re‑render of functional components when props don’t change.

const ListItem = React.memo(function ListItem({ value }) { console.log('Render', value); return <li>{value}</li>; });
29. useTransition for Concurrent UI

Marks updates as non‑urgent to keep the UI responsive.

import { useState, useTransition } from 'react'; const list = Array.from({ length: 20000 }, (_, i) => `Item ${i}`); export default function FilterList() { const [term, setTerm] = useState(''); const [isPending, startTransition] = useTransition(); const filtered = list.filter(i => i.includes(term)); return ( <> <input onChange={e => startTransition(() => setTerm(e.target.value))} /> {isPending ? <p>Loading...</p> : <ul>{filtered.map(i => <li key={i}>{i}</li>)}</ul>} </> ); }
30. Testing with React Testing Library

Write tests focusing on user interactions and output.

/* Counter.test.jsx */ import { render, fireEvent } from '@testing-library/react'; import Counter from './Counter'; test('increments counter', () => { const { getByText } = render(<Counter />); const btn = getByText(/count/i); fireEvent.click(btn); expect(btn.textContent).toBe('Count: 1'); });

React.js Reference Links

1. Official React Documentation

The official guide from the React team, including concepts, APIs, and tutorials.

https://react.dev/learn

2. React API Reference

Detailed reference of React’s APIs, components, and hooks.

https://react.dev/reference

3. React GitHub Repository

Official source code and issue tracker for React on GitHub.

https://github.com/facebook/react

4. React Router Documentation

Routing library for React apps (used with SPAs).

https://reactrouter.com/en/main

5. Redux Documentation

State management library commonly used with React.

https://redux.js.org/

6. React Testing Library

Recommended testing approach that focuses on user behavior.

https://testing-library.com/docs/react-testing-library/intro/

7. Create React App (CRA)

Official tool to scaffold React applications quickly.

https://create-react-app.dev/

8. React Hooks Cheatsheet

Quick overview of built-in hooks and their usage.

https://react-hooks-cheatsheet.com/

9. React Projects and Examples

Community-contributed project ideas and examples to practice React.

https://github.com/facebook/react/issues/1

10. freeCodeCamp React Curriculum

Hands-on React tutorials for beginners to advanced users.

https://www.freecodecamp.org/learn/front-end-development-libraries/#react