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

🚀 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