Complete React JS Notes (Basic to Advanced)
Introduction to React
React is a JavaScript library for building user interfaces. It enables the development of reusable UI
components and is maintained by Facebook.
Creating a React App
You can create a React app using Vite or Create React App (CRA). Example with Vite:
npm create vite@latest my-app
cd my-app
npm install
npm run dev
JSX (JavaScript XML)
JSX allows writing HTML-like syntax in JavaScript. It makes UI code more readable and
expressive.
const element = <h1>Hello, world!</h1>;
Components
Components are reusable pieces of UI. They can be functional or class-based.
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
Props
Props are used to pass data from parent to child components.
function Greeting(props) {
return <h1>Hello, {props.name}</h1>;
}
<Greeting name='Deepak' />
State
State is used to manage data inside a component. React re-renders UI when state changes.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>{count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
useEffect Hook
useEffect is used to perform side effects such as fetching data, setting up subscriptions, or updating
the DOM.
import { useEffect, useState } from 'react';
function DataFetcher() {
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(res => res.json())
.then(data => setData(data));
}, []);
return <ul>{data.map(item => <li key={item.id}>{item.title}</li>)}</ul>;
}
Handling Events
React uses camelCase syntax for event handling. Functions handle interactions like clicks.
function Button() {
function handleClick() {
alert('Button clicked!');
}
return <button onClick={handleClick}>Click Me</button>;
}
Conditional Rendering
You can render components conditionally using if statements or ternary operators.
function UserGreeting(props) {
return props.isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign up.</h1>;
}
Lists and Keys
React renders lists using the map function. Each element should have a unique key.
function NumberList(props) {
const numbers = props.numbers;
return (
<ul>
{numbers.map(num => <li key={num}>{num}</li>)}
</ul>
);
}
Forms in React
Forms in React use controlled components, where form data is handled by state.
function MyForm() {
const [name, setName] = useState('');
function handleSubmit(e) {
e.preventDefault();
alert('Submitted: ' + name);
}
return (
<form onSubmit={handleSubmit}>
<input type='text' value={name} onChange={(e) => setName(e.target.value)} />
<button type='submit'>Submit</button>
</form>
);
}
React Router
React Router is used for navigation in single-page applications (SPA).
import { BrowserRouter as Router, Route, Routes, Link } from 'react-router-dom';
function App() {
return (
<Router>
<nav>
<Link to='/'>Home</Link> | <Link to='/about'>About</Link>
</nav>
<Routes>
<Route path='/' element={<h1>Home</h1>} />
<Route path='/about' element={<h1>About</h1>} />
</Routes>
</Router>
);
}
Context API
The Context API provides a way to share values between components without passing props
manually.
const ThemeContext = React.createContext('light');
function App() {
return (
<ThemeContext.Provider value='dark'>
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
return <ThemedButton />;
}
function ThemedButton() {
const theme = React.useContext(ThemeContext);
return <button>{theme}</button>;
}
Custom Hooks
Custom hooks allow you to reuse logic between components.
function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(count + 1);
return { count, increment };
}
function CounterComponent() {
const { count, increment } = useCounter(5);
return (
<div>
<p>{count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
React Fragments
Fragments let you group elements without adding extra nodes to the DOM.
function Columns() {
return (
<>
<td>Hello</td>
<td>World</td>
</>
);
}
React.memo
React.memo is used to optimize performance by memoizing functional components.
const MyComponent = React.memo(function(props) {
return <h1>{props.value}</h1>;
});
Lazy Loading and Suspense
React supports lazy loading components to improve performance.
import React, { Suspense, lazy } from 'react';
const LazyComponent = lazy(() => import('./MyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
Redux (State Management)
Redux is a state management library often used with React for large applications.
import { createStore } from 'redux';
function reducer(state = { count: 0 }, action) {
switch(action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
default:
return state;
}
}
const store = createStore(reducer);
store.dispatch({ type: 'INCREMENT' });
console.log(store.getState());
React + TypeScript
React works seamlessly with TypeScript for type safety.
type Props = { name: string };
function Welcome({ name }: Props) {
return <h1>Hello, {name}</h1>;
}