BlogCheatsheetReactJS Cheatsheet
blog-image
Cheatsheet
Popular
#Cheatsheet
#React

ReactJS Cheatsheet

A compact and developer-friendly ReactJS Cheatsheet covering core concepts, essential hooks, routing, performance tips, and modern React 18 features all in one place.

IN
Imtiyaz Nandasaniya
@code.clash
12

Table of Content

๐Ÿš€ Getting Startedโš›๏ธ JSX๐Ÿงฑ Components and Props๐Ÿ”ง Functional Components๐Ÿ›  Destructuring Props๐Ÿงฉ Default Props๐Ÿ“ฆ Passing Children๐Ÿ“ PropTypes๐ŸŽฃ React Hooks๐Ÿง  useState๐Ÿ” useEffect๐Ÿงต useContext๐Ÿช useRefโš™๏ธ useReducer๐Ÿง  useMemo๐Ÿ”„ useCallback๐Ÿงฉ Custom Hooks๐Ÿช„ useId๐Ÿงฎ useDeferredValue๐ŸŒ€ useTransition๐Ÿ“ก useSyncExternalStore๐Ÿช„ useLayoutEffect๐Ÿงต useInsertionEffect๐Ÿง  Event Handling๐Ÿ–ฑ Basic Event๐ŸŽฏ Event ObjectโŒ Prevent Default๐Ÿ”€ Conditional Renderingโ“ Ternary Operatorโœ… Logical AND๐Ÿ”„ if-else in Functions๐Ÿ“‹ Lists and Keys๐Ÿ“ Rendering Lists๐Ÿ”‘ Key Warning๐Ÿ“ Forms and Inputs๐ŸŽ› Controlled Components๐Ÿ”“ Uncontrolled Components๐Ÿ“ค Handling Form Submissionโœ… Basic Validation๐Ÿงช Using Libraries๐ŸŽจ Styling๐ŸŽจ Inline Styles๐Ÿงฉ CSS Modules๐ŸŽจ Styled Components๐ŸŒ€ Tailwind CSS๐Ÿงญ Routing (React Router v6)๐Ÿ”— Basic Setup๐Ÿงฌ Dynamic Route๐Ÿ“ useNavigate / useParams๐Ÿงฉ Nested Routes๐Ÿ”„ State Management๐Ÿงฉ Context API๐Ÿ›  Redux Toolkit๐Ÿงช Other Librariesโšก Performance Optimization๐Ÿง  React.memo๐Ÿงฎ useMemo & useCallbackโณ Lazy Loading๐Ÿ” DevTools๐Ÿงช Testingโœ… Unit Testing with RTL + Jest๐Ÿงญ Integration Testing๐Ÿšฆ E2E Testing๐Ÿ›‘ Error Boundaries๐Ÿšช Portals๐Ÿšจ Strict Modeโš›๏ธ React 18+ Concurrent Features๐Ÿงต startTransition๐Ÿงƒ Automatic Batching๐ŸŒ React Server Components (RSC)๐Ÿ”ง DevTools & Ecosystem๐Ÿš€ Deployment๐Ÿ“š Resources

๐Ÿš€ Getting Started

import React from 'react';
import ReactDOM from 'react-dom/client';
 
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

๐Ÿ’ก TIP

Always wrap your root component inside StrictMode during development to catch potential issues early.


โš›๏ธ JSX

const element = <h1>Hello, world!</h1>;
  • JSX is a syntax extension that looks like HTML, used to describe UI in React.
  • JSX is transpiled to React.createElement() calls under the hood.
  • Expressions like {1 + 2} or {props.name} can be embedded inside JSX.

๐Ÿ’ก NOTE

JSX must return a single parent element. Use fragments (<>...</>) if needed.


๐Ÿงฑ Components and Props

Components are the building blocks of a React application. Each component represents a part of the user interface.

๐Ÿ”ง Functional Components

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
 
const App = () => <Welcome name="Imtiyaz" />;

๐Ÿ’ก TIP

Always use functional components with hooks for simplicity and performance.

๐Ÿ›  Destructuring Props

const Welcome = ({ name }) => <h1>Hello, {name}</h1>;

๐Ÿงฉ Default Props

const Greeting = ({ name = 'Guest' }) => <p>Hello, {name}</p>;

๐Ÿ’ฌ TIP

Use default props to avoid errors from undefined values.

๐Ÿ“ฆ Passing Children

const Card = ({ children }) => <div className="card">{children}</div>;
 
<Card><p>Content</p></Card>

๐Ÿ“ PropTypes

import PropTypes from 'prop-types';
MyComponent.propTypes = {
  message: PropTypes.string
};

๐ŸŽฃ React Hooks

Hooks allow you to use state and lifecycle features in functional components.

๐Ÿง  useState

const [count, setCount] = useState(0);
  • Manages state in functional components.
  • Useful for counters, toggles, form inputs, etc.

๐Ÿ” useEffect

useEffect(() => {
  console.log("Component mounted or updated");
}, [dependencies]);
  • Used for side effects like API calls, subscriptions, and timeouts.

โš ๏ธ NOTE

Cleanup functions can be returned inside useEffect.

๐Ÿงต useContext

const value = useContext(MyContext);
  • Share global data (auth, theme, locale) across components.
  • Avoids prop drilling.

๐Ÿช useRef

const inputRef = useRef();
<input ref={inputRef} />;
  • Mutable value that persists across renders.
  • Common for focusing inputs or triggering DOM events.

โš™๏ธ useReducer

const reducer = (state, action) => {
  switch(action.type) {
    case 'increment': return { count: state.count + 1 };
    default: return state;
  }
};
 
const [state, dispatch] = useReducer(reducer, { count: 0 });
  • Alternative to useState for complex logic or multiple state transitions.

๐Ÿง  useMemo

const memoized = useMemo(() => computeHeavy(val), [val]);
  • Prevents recalculating expensive computations on every render.

๐Ÿ”„ useCallback

const handleClick = useCallback(() => doSomething(), []);
  • Returns memoized version of a callback function.

๐Ÿงฉ Custom Hooks

function useToggle(initial = false) {
  const [state, setState] = useState(initial);
  const toggle = () => setState(s => !s);
  return [state, toggle];
}

๐Ÿ›  TIP

Prefix custom hook names with "use" so React can handle them properly.

๐Ÿช„ useId

const id = useId();
<label htmlFor={id}>Name</label>
<input id={id} />
  • Generates unique IDs that are consistent across the server and client.

๐Ÿงฎ useDeferredValue

const deferredValue = useDeferredValue(inputValue);
  • Defers re-rendering of non-urgent updates for better performance.

๐ŸŒ€ useTransition

const [isPending, startTransition] = useTransition();
  • Lets you mark updates as non-urgent.
  • Improves responsiveness for transitions.

๐Ÿ“ก useSyncExternalStore

const snap = useSyncExternalStore(subscribe, getSnapshot);
  • Used for subscribing to external stores in a consistent way.

๐Ÿช„ useLayoutEffect

useLayoutEffect(() => {
  // Read DOM or apply sync layout changes
}, []);
  • Similar to useEffect, but Runs after DOM mutations but before the browser paints
  • Can block painting if heavy โ€” use carefully to avoid jank
  • Affects performance more than useEffect if misused

๐Ÿงต useInsertionEffect

useInsertionEffect(() => {
  // Insert styles before layout and paint
}, []);
  • Runs before any DOM mutations, even before useLayoutEffect
  • Allows injecting styles into the DOM before rendering

๐Ÿง  Event Handling

๐Ÿ–ฑ Basic Event

function handleClick() {
  alert('Clicked!');
}
 
<button onClick={handleClick}>Click Me</button>

๐ŸŽฏ Event Object

<input onChange={(e) => console.log(e.target.value)} />

โŒ Prevent Default

<form onSubmit={(e) => e.preventDefault()}>...</form>

๐Ÿ’ก TIP

React uses Synthetic Events, which are cross-browser wrappers around native events.


๐Ÿ”€ Conditional Rendering

โ“ Ternary Operator

{isLoggedIn ? <Dashboard /> : <Login />}

โœ… Logical AND

{isOnline && <span>Online</span>}

๐Ÿ”„ if-else in Functions

function renderStatus() {
  if (loading) return <Loading />;
  if (error) return <Error />;
  return <Data />;
}

๐Ÿ“‹ Lists and Keys

๐Ÿ“ Rendering Lists

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

๐Ÿ”‘ Key Warning

  • Keys help React identify which items have changed.
  • Avoid using array index as key unless the list is static.

๐Ÿ“ Forms and Inputs

๐ŸŽ› Controlled Components

const [input, setInput] = useState('');
<input value={input} onChange={e => setInput(e.target.value)} />

๐Ÿ”“ Uncontrolled Components

<input ref={inputRef} />

๐Ÿ“ค Handling Form Submission

function handleSubmit(e) {
  e.preventDefault();
  console.log("Submitted", input);
}

โœ… Basic Validation

if (input.length < 3) setError("Too short");

๐Ÿงช Using Libraries

  • Formik: Form state + validation
  • React Hook Form: Better performance, works with uncontrolled components

๐Ÿงผ NOTE

For complex forms, prefer libraries over custom logic.


๐ŸŽจ Styling

๐ŸŽจ Inline Styles

<div style={{ color: 'red' }}>Hi</div>

๐Ÿงฉ CSS Modules

import styles from './App.module.css';
<div className={styles.title}></div>

๐ŸŽจ Styled Components

const Button = styled.button`
  background: purple;
  color: white;
`;

๐ŸŒ€ Tailwind CSS

<button className="bg-blue-500 text-white px-4 py-2">Click</button>

๐ŸŽจ TIP

Use BEM or CSS Modules for scalable styles.


๐Ÿงญ Routing (React Router v6)

๐Ÿ”— Basic Setup

import { BrowserRouter, Routes, Route } from 'react-router-dom';
 
<BrowserRouter>
  <Routes>
    <Route path="/about" element={<About />} />
    <Link to="/about">About</Link>
  </Routes>
</BrowserRouter>

๐Ÿงฌ Dynamic Route

<Route path="/user/:id" element={<User />} />

๐Ÿ“ useNavigate / useParams

const navigate = useNavigate();
const { id } = useParams();

๐Ÿงฉ Nested Routes

<Route path="/dashboard" element={<Dashboard />}>
  <Route path="settings" element={<Settings />} />
</Route>

๐Ÿ”„ State Management

๐Ÿงฉ Context API

const ThemeContext = React.createContext();
<ThemeContext.Provider value={value}>
  <App />
</ThemeContext.Provider>

๐Ÿ›  Redux Toolkit

const store = configureStore({ reducer: rootReducer });
  • Slices, actions, and reducers in one place
  • DevTools integration

๐Ÿงช Other Libraries

  • Zustand: Minimal API, easy to learn
  • Jotai: Atomic design, flexible
  • Recoil: Fine-grained state syncing

โšก Performance Optimization

๐Ÿง  React.memo

const MemoComp = React.memo(MyComponent);

๐Ÿงฎ useMemo & useCallback

Memoize expensive values or functions.

โณ Lazy Loading

const LazyComp = React.lazy(() => import('./MyComp'));
  • Wrap with <Suspense> for fallback UI

๐Ÿ” DevTools

  • React Profiler: Detect unnecessary re-renders

๐Ÿšจ TIP

Minimize re-renders and use memoization for heavy components.


๐Ÿงช Testing

โœ… Unit Testing with RTL + Jest

render(<Button />);
expect(screen.getByText("Click Me")).toBeInTheDocument();

๐Ÿงญ Integration Testing

  • Check interaction across components

๐Ÿšฆ E2E Testing

  • Cypress: Fast, visual
  • Playwright: Powerful automation

๐Ÿ›‘ Error Boundaries

class ErrorBoundary extends React.Component {
  state = { hasError: false };
  static getDerivedStateFromError() {
    return { hasError: true };
  }
  render() {
    return this.state.hasError ? <h1>Error</h1> : this.props.children;
  }
}

โš ๏ธ Use class components for error boundaries.


๐Ÿšช Portals

ReactDOM.createPortal(<Modal />, document.body);

๐Ÿ”น Use for modals, tooltips, etc.


๐Ÿšจ Strict Mode

<React.StrictMode>
  <App />
</React.StrictMode>

๐Ÿ“ Dev-only checks for side effects and potential issues.


โš›๏ธ React 18+ Concurrent Features

๐Ÿงต startTransition

startTransition(() => setInput(val));

๐Ÿงƒ Automatic Batching

Multiple state updates are batched automatically.


๐ŸŒ React Server Components (RSC)

// app/page.js
export default async function Page() {
  const data = await fetchData();
  return <div>{data.name}</div>;
}

๐Ÿ“ Used in frameworks like Next.js. No client-side JS.


๐Ÿ”ง DevTools & Ecosystem

  • React DevTools โ€“ inspect components, state, props
  • Redux DevTools โ€“ debug Redux state changes
  • Linting โ€“ ESLint + Prettier for clean code

๐Ÿš€ Deployment

  • Build: npm run build
  • Host: Vercel, Netlify, GitHub Pages
  • Env Vars: .env, .env.production

๐Ÿ“š Resources


โœ… TIP

Stick to functional components and master hooks โ€” thatโ€™s where modern React is headed.

๐Ÿงผ NOTE

Donโ€™t reinvent the wheel. Use community libraries when possible (e.g., react-hook-form, react-query, zustand).

IN

Imtiyaz Nandasaniya

@code.clash

I&apos;m a passionate content creator and full-stack developer who loves sharing knowledge with the developer community. Through my Instagram @code.clash, I create daily content about programming, web development, and tech insights.

0K+
Followers
0
Posts

Comments

0

Leave a Comment