React
Updated: September 10, 2025Categories: Languages, Frontend, Web
Printed from:
React Cheatsheet
1. Installation and Setup
Create React App
Bash
1234npx create-react-app my-app
cd my-app
npm start
Vite
Bash
12345npm create vite@latest my-app -- --template react
cd my-app
npm install
npm run dev
Manual Setup
Bash
1234npm init -y npm install react react-dom npm install -D @babel/core @babel/preset-react webpack webpack-cli webpack-dev-server babel-loader
2. Component Basics
Functional Components
jsx
123456789function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
// Arrow Function Syntax
const Greeting = ({ name }) => {
return <h1>Hello, {name}!</h1>;
};
Class Components
jsx
12345678import React, { Component } from 'react';
class Greeting extends Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
JSX
jsx
1234const element = <h1 className="greeting">Hello, world!</h1>;
const expr = <div>{2 + 2}</div>;
const list = <ul>{items.map(item => <li key={item.id}>{item.name}</li>)}</ul>;
3. Props and PropTypes
Passing Props
jsx
1234567891011121314151617import PropTypes from 'prop-types';
function UserProfile({ name, age }) {
return (
<div>
<p>Name: {name}</p>
<p>Age: {age}</p>
</div>
);
}
UserProfile.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number
};
UserProfile.defaultProps = {
age: 0
};
4. State Management
useState Hook
jsx
12345678910import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
Class Component State
jsx
1234567891011121314151617class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
incrementCount = () => {
this.setState((prevState) => ({ count: prevState.count + 1 }));
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.incrementCount}>Increment</button>
</div>
);
}
}
5. Event Handling
Basic Event Handling
jsx
12345678910111213141516function Button() {
const handleClick = (e) => {
console.log('Button clicked', e);
};
return <button onClick={handleClick}>Click me</button>;
}
function Form() {
const handleChange = (e) => {
console.log(e.target.value);
};
return <input type="text" onChange={handleChange} />;
}
6. Lifecycle Methods and useEffect
useEffect Hook
jsx
1234567891011121314151617181920import React, { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
// Component Did Mount / Update
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
// Cleanup function (Component Will Unmount)
return () => {
// Cancel subscriptions, clear timers
};
}, []); // Empty dependency array means run once
return data ? <div>{data}</div> : <div>Loading...</div>;
}
7. Hooks
useState
jsx
12const [state, setState] = useState(initialValue);
useEffect
jsx
1234567useEffect(() => {
// Side effect code
return () => {
// Cleanup code
};
}, [dependencies]); // Optional dependency array
useContext
jsx
12345678910111213const ThemeContext = React.createContext('light');
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
const theme = useContext(ThemeContext);
return <div>{theme}</div>;
}
Custom Hook
jsx
1234567891011121314151617function useWindowSize() {
const [size, setSize] = useState({ width: 0, height: 0 });
useEffect(() => {
const handleResize = () => {
setSize({ width: window.innerWidth, height: window.innerHeight });
};
window.addEventListener('resize', handleResize);
handleResize(); // Initial call
return () => window.removeEventListener('resize', handleResize);
}, []);
return size;
}
8. Context API
jsx
123456789101112131415const MyContext = React.createContext(defaultValue);
function Provider({ children }) {
const [state, setState] = useState(initialState);
return (
<MyContext.Provider value={{ state, setState }}>
{children}
</MyContext.Provider>
);
}
function Consumer() {
const { state, setState } = useContext(MyContext);
return <div>{state}</div>;
}
9. Conditional Rendering
jsx
12345678910111213function Greeting({ isLoggedIn }) {
// If statement
if (!isLoggedIn) {
return <LoginButton />;
}
// Ternary operator
return isLoggedIn ? <UserProfile /> : <LoginForm />;
// Logical AND
return isLoggedIn && <WelcomeMessage />;
}
10. Lists and Keys
jsx
123456function TodoList({ todos }) {
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}
11. Forms and Controlled Components
jsx
12345678910111213function Form() {
const [value, setValue] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
console.log(value);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={value}
onChange={(e) => setValue(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
);
}
12. Routing (React Router v6)
jsx
12345678910111213import { BrowserRouter, Routes, Route, Link, useParams } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/user/:id" element={<UserProfile />} />
</Routes>
</BrowserRouter>
);
}
function UserProfile() {
const { id } = useParams();
return <div>User ID: {id}</div>;
}
13. State Management Libraries
Redux (Basic Setup)
jsx
12345678910111213141516171819202122232425import { createStore } from 'redux';
import { Provider, useSelector, useDispatch } from 'react-redux';
const initialState = { count: 0 };
function counterReducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
default:
return state;
}
}
const store = createStore(counterReducer);
function Counter() {
const count = useSelector(state => state.count);
const dispatch = useDispatch();
return (
<div>
<p>Count: {count}</p>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>
Increment
</button>
</div>
);
}
14. Performance Optimization
jsx
123456789101112131415const MemoizedComponent = React.memo(MyComponent);
function ExpensiveComponent({ data }) {
const memoizedValue = useMemo(() => {
return computeExpensiveValue(data);
}, [data]);
const memoizedCallback = useCallback(() => {
doSomething(data);
}, [data]);
// Lazy loading
const LazyComponent = React.lazy(() => import('./LazyComponent'));
}
15. Testing
jsx
123456789101112131415import { render, screen, fireEvent } from '@testing-library/react';
test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});
test('button click increments counter', () => {
render(<Counter />);
const button = screen.getByText('Increment');
fireEvent.click(button);
expect(screen.getByText('Count: 1')).toBeInTheDocument();
});
16. Build and Deployment
Bash
1234567# Create production build
npm run build
# Deployment (Create React App)
npm install -g serve
serve -s build
17. Common Patterns and Best Practices
- Keep components small and focused
- Use functional components and hooks
- Lift state up when multiple components need to share state
- Use prop drilling sparingly, prefer Context or state management libraries
- Avoid unnecessary re-renders with React.memo, useMemo, and useCallback
18. Error Boundaries
jsx
1234567891011121314151617181920212223class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
logErrorToService(error, errorInfo);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
19. TypeScript Integration
tsx
12345678910111213import React, { FC } from 'react';
interface UserProps {
name: string;
age?: number;
}
const User: FC<UserProps> = ({ name, age = 0 }) => {
return (
<div>
<p>Name: {name}</p>
<p>Age: {age}</p>
</div>
);
};
Note: This cheatsheet covers modern React practices with a focus on functional components and hooks. Always refer to the official React documentation for the most up-to-date information.
Continue Learning
Discover more cheatsheets to boost your productivity