React
React
How to React
This is the fastest way React in a building situation, more yapping is listed after.
JSX ≠ HTML
Use `` for dynamic content, `className` instead of `class`, and `htmlFor` instead of `for`.
<h1>{title}</h1> // ✅ Correct
<label htmlFor="input">Name</label> // ✅ CorrectReact Doesn’t Update State Immediately
State updates are async. Always use functional updates if relying on previous state.
setCount(count + 1); console.log(count); // ❌ Still old value setCount(prev => prev + 1); // ✅ Correct
No Direct DOM Manipulation
Don’t use `document.getElementById`. Use `useRef` instead.
const inputRef = useRef(null);
<input ref={inputRef} />;Props Are Immutable
Pass data down but never modify props inside a component.
function Child({ count }) {
count += 1; // ❌ Wrong
}Hooks Have Rules
Only call hooks at the top level. Never use inside loops, conditions, or nested functions.
// ✅ Correct
useEffect(() => { console.log("Mounted"); }, []);
// ❌ Wrong
if (someCondition) { useEffect(() => { ... }); } Always Use a Unique Key in Lists
Keys help React optimize rendering.
{items.map(item => <div key={item.id}>{item.name}</div>)} `useEffect` Runs AFTER Render
It doesn’t block the UI. Cleanup functions handle unmounting.
useEffect(() => {
const interval = setInterval(() => console.log("Tick"), 1000);
return () => clearInterval(interval);
}, []);Event Handling is Different
Use camelCase for event names and pass functions, don’t call them.
<button onClick={handleClick}>Click</button> // ✅ Correct
<button onClick={handleClick()}>Click</button> // ❌ WrongForms? Use Controlled Components
Don’t use `document.getElementById`, use state to handle inputs.
const [name, setName] = useState("");
<input value={name} onChange={e => setName(e.target.value)} />;Use <Link> Instead of <a> in React Router
React Router prevents full-page reloads.
<Link to="/about">About</Link> // ✅ Correct <a href="/about">About</a> // ❌ Wrong
No Global State? Use Context API or Redux
Context API for simple cases, Redux/Zustand/Recoil for complex state management.
const UserContext = createContext();
function App() {
return <UserContext.Provider value={user}>{children}</UserContext.Provider>;
}CSS Modules Auto-Scope Class Names
Import styles properly instead of using global CSS.
import styles from "./Button.module.css";
<button className={styles.btn}>Click</button>;Next.js Has Built-in Routing & SSR
Use file-based routing and server-side rendering (`getServerSideProps`).
export async function getServerSideProps() {
const data = await fetchData();
return { props: { data } };
}Avoid Unnecessary Renders
Use `React.memo`, `useMemo`, and `useCallback` for performance optimizations.
const MemoizedComponent = React.memo(MyComponent); const cachedFunction = useCallback(() => doSomething(), []);
React is Declarative, Not Imperative
Don’t manually manipulate the DOM. Change state, let React handle UI updates.
setCount(5); // ✅ Let React re-render
document.getElementById("counter").innerText = 5; // ❌ WrongReact Basics
JSX Syntax
// 🔹 JSX allows HTML-like syntax in JavaScript
const element = <h1>Hello, World!</h1>;
// 🔹 Embed expressions with curly braces
const name = "Alice";
const greeting = <p>Hello, {name}!</p>;
// 🔹 Self-closing tags for elements without children
const image = <img src="logo.png" alt="Logo" />;Components
// 🎣 Functional Component
function Greeting(props) {
return <h1>Hello {props.name}</h1>;
}
// ⚙️ Class Component
class Greeting extends React.Component {
render() {
return <h1>Hello {this.props.name}</h1>;
}
}State & Props
// 🔹 useState Hook (Functional Component)
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}Event Handling
// 🔹 Handling Events in React
function Button() {
function handleClick() {
alert("Button clicked!");
}
return <button onClick={handleClick}>Click me</button>;
}
// ⚠️ Do not use handleClick() instead of handleClick in onClick!useEffect Hook
// 🔹 useEffect: Runs after render
import { useEffect, useState } from "react";
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(prev => prev + 1);
}, 1000);
return () => clearInterval(interval); // Cleanup function
}, []); // Empty array = run only on mount
return <p>Time: {seconds} seconds</p>;
}useMemo & useCallback
// 🔹 useMemo: Optimize expensive calculations
import { useMemo, useState } from "react";
function ExpensiveCalculation({ num }) {
const squared = useMemo(() => {
console.log("Calculating...");
return num * num;
}, [num]);
return <p>Squared: {squared}</p>;
}React Router
// 🔹 React Router Basic Setup
import { BrowserRouter, Routes, Route, Link } 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="/about" element={<About />} />
</Routes>
</BrowserRouter>
);
}Global State: Context API
// 🔹 Creating a Context
import { createContext, useContext, useState } from "react";
const ThemeContext = createContext();
function ThemeProvider({ children }) {
const [theme, setTheme] = useState("light");
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
function ChildComponent() {
const { theme, setTheme } = useContext(ThemeContext);
return <button onClick={() => setTheme("dark")}>Change Theme</button>;
}React Performance Optimization
// 🔹 React.memo to Prevent Unnecessary Re-renders
import React from "react";
const MemoizedComponent = React.memo(({ count }) => {
console.log("Rendered!");
return <p>Count: {count}</p>;
});Fetching Data (Axios, Fetch API)
// 🔹 Fetch API Example
import { useEffect, useState } from "react";
function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(json => setData(json));
}, []);
return <pre>{JSON.stringify(data, null, 2)}</pre>;
}Error Boundaries
// 🔹 Handling Errors in React
import React from "react";
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>Something went wrong.</h1>;
}
return this.props.children;
}
}React Quirks & Best Practices
// 🔹 Unique Keys in Lists
const items = ["Apple", "Banana", "Cherry"];
const list = items.map((item, index) => <li key={index}>{item}</li>); // ⚠️ Bad practice!
const listFixed = items.map((item) => <li key={item}>{item}</li>); // ✅ Good practice
// 🔹 Avoid Mutating State Directly
setState([...state, newItem]); // ✅ Correct way
state.push(newItem); // ⚠️ Incorrect wayNext.js-Specific Topics
// 🔹 getStaticProps for Static Site Generation
export async function getStaticProps() {
const res = await fetch("https://jsonplaceholder.typicode.com/posts");
const posts = await res.json();
return { props: { posts } };
}
function Home({ posts }) {
return <pre>{JSON.stringify(posts, null, 2)}</pre>;
}Why Solo Dev?
This reference website is not for beginners
Solo Dev is strictly for devs who already know the game and need a beautiful cheat sheet on their second monitor which looks better than GeeksforGeeks
this portion goes away when you shrink the screen ;)
