Introduction
React is a popular JavaScript library used to build user interfaces, especially for single-page applications. It was developed by Facebook and is widely used due to its speed, reusability, and simplicity. This cheatsheet is designed to help you understand React by covering the most important topics in simple language with small code examples.
1. JSX (JavaScript XML)
Definition: JSX is a syntax extension for JavaScript. It looks like HTML but works inside JavaScript.
const element = <h1>Hello, World!</h1>;
Important: JSX must be inside a single parent element and you must close all tags.
2. Components
Definition: Components are the building blocks of React. They are reusable pieces of code.
Function Component Example:
function Greeting() {
return <h1>Welcome</h1>;
}
Important: Component names should start with a capital letter.
3. Props
Definition: Props (short for properties) are used to pass data from parent to child components.
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
// Usage
<Welcome name="John" />
Important: Props are read-only.
4. State
Definition: State is used to store data inside a component.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>{count}</p>
<button onClick={() => setCount(count + 1)}>Add</button>
</div>
);
}
Important: State changes cause re-rendering.
5. useEffect Hook
Definition: useEffect
is used to run code after the component renders.
import { useEffect } from 'react';
useEffect(() => {
console.log('Component rendered');
}, []);
Important: The second argument is a dependency array. Use []
to run once.
6. Conditional Rendering
Definition: You can render elements conditionally using if
or ? :
.
function User(props) {
return props.isLoggedIn ? <h1>Welcome</h1> : <h1>Please log in</h1>;
}
7. Lists and Keys
Definition: Use .map()
to render lists. Always use a unique key
.
const items = ['A', 'B', 'C'];
const list = items.map((item, index) => <li key={index}>{item}</li>);
Important: Keys help React identify elements for efficient re-rendering.
8. Event Handling
Definition: You can handle events using camelCase syntax.
function MyButton() {
function handleClick() {
alert('Clicked!');
}
return <button onClick={handleClick}>Click</button>;
}
9. Forms
Definition: Forms in React use controlled components.
function Form() {
const [name, setName] = useState('');
function handleChange(e) {
setName(e.target.value);
}
return <input value={name} onChange={handleChange} />;
}
10. Lifting State Up
Definition: When multiple components need access to the same state, lift it to their common parent.
// Parent Component
function Parent() {
const [data, setData] = useState('');
return (
<>
<ChildInput onChange={setData} />
<ChildOutput value={data} />
</>
);
}
11. useRef Hook
Definition: useRef
is used to store a reference to a DOM element or value that does not cause re-render.
import { useRef } from 'react';
function InputFocus() {
const inputRef = useRef();
function focusInput() {
inputRef.current.focus();
}
return (
<>
<input ref={inputRef} />
<button onClick={focusInput}>Focus</button>
</>
);
}
12. React Router (Basic)
Definition: React Router is used for navigation in single-page apps.
npm install react-router-dom
import { BrowserRouter, Routes, Route } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
);
}
13. Context API
Definition: Used to pass data without props.
const MyContext = React.createContext();
function App() {
return (
<MyContext.Provider value="Hello">
<Child />
</MyContext.Provider>
);
}
function Child() {
const value = useContext(MyContext);
return <p>{value}</p>;
}
14. Fragments
Definition: Used to group multiple elements without adding extra DOM nodes.
return (
<>
<h1>Title</h1>
<p>Paragraph</p>
</>
);
15. useMemo and useCallback
useMemo: Caches calculated values.
const result = useMemo(() => computeExpensiveValue(a, b), [a, b]);
useCallback: Caches functions.
const memoizedCallback = useCallback(() => doSomething(a, b), [a, b]);
16. Error Boundaries
Definition: Catches errors in components.
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
render() {
if (this.state.hasError) {
return <h1>Error occurred.</h1>;
}
return this.props.children;
}
}
17. Custom Hooks
Definition: You can write your own hooks to reuse logic.
function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(count + 1);
return [count, increment];
}
18. React Developer Tools
Definition: A browser extension that helps debug React components.
Install from Chrome or Firefox extension store.
19. Controlled vs Uncontrolled Components
Definition
- Controlled components store form data in React state.
- Uncontrolled components use the DOM directly.
Controlled Example
function ControlledInput() {
const [value, setValue] = useState('');
return <input value={value} onChange={(e) => setValue(e.target.value)} />;
}
Uncontrolled Example
function UncontrolledInput() {
const inputRef = useRef();
function handleSubmit() {
alert(inputRef.current.value);
}
return (
<>
<input ref={inputRef} />
<button onClick={handleSubmit}>Submit</button>
</>
);
}
20. Lazy Loading Components
Definition: Load components only when needed to reduce initial load time.
import { lazy, Suspense } from 'react';
const LazyComponent = lazy(() => import('./MyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
21. Code Splitting
Definition: Automatically split code into smaller files that load as needed. This is usually done with dynamic import()
.
const MyComponent = React.lazy(() => import('./MyComponent'));
22. Forward Refs
Definition: Allows a parent component to directly access a child’s DOM node.
const Input = React.forwardRef((props, ref) => (
<input ref={ref} {...props} />
));
23. Portals
Definition: Render elements outside the root component (useful for modals or tooltips).
ReactDOM.createPortal(
<ModalContent />,
document.getElementById('modal-root')
);
24. Strict Mode
Definition: Helps identify problems in your React app during development.
<React.StrictMode>
<App />
</React.StrictMode>
25. Reconciliation
Definition: React’s process of updating the DOM efficiently by comparing the new tree with the previous one and applying minimal changes.
Important: Avoid direct DOM manipulation; React handles it better and faster.
26. Virtual DOM
Definition: A lightweight copy of the real DOM. React updates this first, then reflects only necessary changes in the real DOM.
27. React.memo
Definition: Prevents unnecessary re-renders by memoizing components.
const MyComponent = React.memo(function MyComponent(props) {
return <div>{props.name}</div>;
});
28. PureComponent (Class Only)
Definition: In class components, PureComponent
does shallow comparison of props and state to reduce re-renders.
class MyComponent extends React.PureComponent {
render() {
return <div>{this.props.value}</div>;
}
}
29. Higher-Order Components (HOC)
Definition: A function that takes a component and returns a new component.
function withLogging(WrappedComponent) {
return function(props) {
console.log('Rendering');
return <WrappedComponent {...props} />;
};
}
30. Error Handling in useEffect
Important: You can't use try-catch
for async code directly in useEffect
. Use an inner async function.
useEffect(() => {
async function fetchData() {
try {
const res = await fetch('url');
const data = await res.json();
} catch (err) {
console.error(err);
}
}
fetchData();
}, []);
31. Environment Variables in React
Definition: Use .env
files with REACT_APP_
prefix.
REACT_APP_API_URL=https://api.example.com
console.log(process.env.REACT_APP_API_URL);
32. Default Props and PropTypes
Definition: PropTypes are used for type-checking, and defaultProps
are fallback values.
import PropTypes from 'prop-types';
function Greeting({ name }) {
return <h1>Hello, {name}</h1>;
}
Greeting.propTypes = {
name: PropTypes.string
};
Greeting.defaultProps = {
name: 'Guest'
};
33. Strict Type Checking with TypeScript
Definition: React apps can be built with TypeScript for safer code.
type Props = {
name: string;
};
function Greeting({ name }: Props) {
return <h1>Hello, {name}</h1>;
}
34. React State Management Tools
Popular Libraries
- Redux
- Zustand
- Jotai
- Recoil
- MobX
Each helps manage global state outside of components.
35. React Testing
Libraries
Jest
– Unit testing
React Testing Library
– DOM testing
test('renders welcome message', () => {
render(<Greeting name="John" />);
expect(screen.getByText('Hello, John')).toBeInTheDocument();
});
Conclusion
React is a powerful and flexible library. This extended cheatsheet includes almost all the core concepts and important tools used in real-world applications. Once you're comfortable with these topics, you can build fast, interactive, and scalable front-end apps. Keep practicing and refer to this cheatsheet as a quick guide during development.