Build powerful user interfaces with React using reusable
components, props, state, and hooks.
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.
Install React using Create React App (CRA):
npx create-react-app my-app
cd my-app
npm start
JSX allows you to write HTML in JavaScript. It looks like HTML but compiles to React.createElement calls.
const element = <h1>Hello, React!</h1>;
A functional component is a simple JavaScript function that returns JSX.
function Welcome() {
return <h1>Welcome to React</h1>;
}
Class-based components include lifecycle methods and state (before Hooks).
class Welcome extends React.Component {
render() {
return <h1>Hello from
Class</h1>;
}
}
Props are used to pass data from parent to child components.
function Greet(props) {
return <h2>Hello, {props.name}!</h2>;
}
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>);
}
React uses camelCase for event names and passes functions as event handlers.
<button onClick={handleClick}>Click Me</button>
You can use if statements or ternary expressions to render elements conditionally.
{isLoggedIn ? <Logout /> : <Login />}
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>);
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
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>;
}
Creates a reference to a DOM element or to persist values across renders.
const inputRef = useRef();
useEffect(() => {
inputRef.current.focus();
}, []);
Memosize expensive calculations and avoid unnecessary recalculations.
const result = useMemo(() => expensiveFn(data), [data]);
Returns a memoized version of a callback function to prevent unnecessary re-renders.
const handleClick = useCallback(() => {
console.log("Clicked");
}, []);
Use controlled components to handle form inputs.
const [name, setName] = useState('');
<input value={name} onChange={e => setName(e.target.value)} />
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>
Methods like componentDidMount, componentDidUpdate, and componentWillUnmount are used to handle side effects.
componentDidMount() {
console.log("Component mounted");
}
Move state to the closest common ancestor of components that need it.
Used when multiple components need access to shared state.
Apply styles dynamically using inline styles or class names.
<div style={{ color: isActive ? 'green' : 'red'
}}>Status</div>
<div className={isActive ? 'active' :
'inactive'}>Status</div>
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> ); }
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> ); }
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> </> ); }
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> ); }
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> ); }
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 };
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');
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>;
});
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>} </> ); }
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'); });
The official guide from the React team, including concepts, APIs, and tutorials.
Detailed reference of React’s APIs, components, and hooks.
Official source code and issue tracker for React on GitHub.
https://github.com/facebook/react
Routing library for React apps (used with SPAs).
https://reactrouter.com/en/main
State management library commonly used with React.
Recommended testing approach that focuses on user behavior.
https://testing-library.com/docs/react-testing-library/intro/
Official tool to scaffold React applications quickly.
Quick overview of built-in hooks and their usage.
https://react-hooks-cheatsheet.com/
Community-contributed project ideas and examples to practice React.
https://github.com/facebook/react/issues/1
Hands-on React tutorials for beginners to advanced users.
https://www.freecodecamp.org/learn/front-end-development-libraries/#react