React

React Cheatsheet — Components, Hooks & Patterns

Thirdy Gayares
18 min read

🎓 What You Will Learn

  • JSX Syntax: Write HTML-like syntax in JavaScript
  • Components: Create reusable, modular UI pieces
  • Props: Pass data from parent to child components
  • State: Manage dynamic data with useState
  • Event Handling: Respond to user interactions
  • Conditional Rendering: Show/hide elements based on conditions
  • Lists & Keys: Render multiple items efficiently
  • Forms: Handle user input and form submission
1

What is React?

React is a JavaScript library for building user interfaces. It makes building interactive web apps easier by breaking your UI into small, reusable pieces called components.

Think of React like LEGO: You build small blocks (components), then combine them to create bigger structures (apps).

2

JSX — JavaScript XML

JSX lets you write HTML-like code in JavaScript. It looks like HTML but it's actually JavaScript under the hood.

jsx-example.jsx
// JSX looks like HTML but it's JavaScript
const name = "Alice";
const element = <h1>Hello, {name}!</h1>;

// JSX gets converted to JavaScript function calls
// const element = React.createElement('h1', null, 'Hello, Alice!');
1JSX Rules
  • • One top-level element (wrap in <div> or <></>)
  • • Use className instead of class
  • • Use htmlFor instead of for
  • • Self-closing tags need / (like <img />)
  • • Use curly braces {} for JavaScript expressions

Hello React! 👋

This is rendered from JSX

Name: John Doe
Skill Level: Intermediate
3

Functional Components

A component is a JavaScript function that returns JSX. It's a reusable piece of UI.

basic-component.jsx
// Functional Component (modern way)
export function Welcome() {
  return (
    <div>
      <h1>Welcome to React!</h1>
      <p>This is a functional component</p>
    </div>
  );
}

// Usage
function App() {
  return <Welcome />;
}
✅ Component naming: Always start with a capital letter (Welcome, UserCard, etc.)
4

Props — Passing Data

Props (properties) let you pass data from a parent component to a child component. Props are like function parameters.

props-example.jsx
// Component that receives props
function Greeting({ name, emoji }) {
  return <h1>{emoji} Hello, {name}!</h1>;
}

// Usage: Pass props as attributes
function App() {
  return (
    <>
      <Greeting name="Alice" emoji="👋" />
      <Greeting name="Bob" emoji="😊" />
      <Greeting name="Charlie" emoji="🎉" />
    </>
  );
}
Props flow downward: Parent → Child (one-way data flow)

Alice

Age: 28

Role: Developer

Bob

Age: 35

Role: Designer

Charlie

Age: 22

Role: Intern

5

State — Dynamic Data

State is data that can change. Use the useState hook to add state to functional components.

state-example.jsx
import { useState } from 'react';

export function Counter() {
  // useState returns [currentValue, functionToUpdate]
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>
    </div>
  );
}
⚠️ Never mutate state directly! Always use the setter function. ❌ count++setCount(count + 1)

Count: 0

Message: Hello!

6

Conditional Rendering

Show or hide elements based on conditions using if statements, ternary operators, or logical AND.

1Ternary Operator
ternary.jsx
{isLoggedIn ? (
  <p>Welcome back!</p>
) : (
  <p>Please log in</p>
)}
2Logical AND
logical-and.jsx
{isAdmin && <button>Delete User</button>}

{isLoading && <p>Loading...</p>}

Please log in to continue

You are a teenager 👦

7

Event Handling

Handle user interactions like clicks, form submissions, and input changes.

event-handlers.jsx
export function EventDemo() {
  const [count, setCount] = useState(0);

  // Click handler
  const handleClick = () => {
    setCount(count + 1);
  };

  // Form submission
  const handleSubmit = (e) => {
    e.preventDefault();  // Prevent page reload
    console.log("Form submitted!");
  };

  return (
    <>
      <button onClick={handleClick}>Click me</button>
      <form onSubmit={handleSubmit}>
        <input type="text" />
        <button type="submit">Submit</button>
      </form>
    </>
  );
}
EventHandlerExample
ClickonClick<button onClick={handleClick}>
Input ChangeonChange<input onChange={(e) => ...}
Form SubmitonSubmit<form onSubmit={handleSubmit}>
Mouse EnteronMouseEnter<div onMouseEnter={...}>
Key PressonKeyPress<input onKeyPress={...}
8

The Children Prop

children is a special prop that contains anything passed between component tags.

children-example.jsx
// Component definition
function Card({ title, children }) {
  return (
    <div>
      <h2>{title}</h2>
      {children}
    </div>
  );
}

// Usage: content between tags becomes children
function App() {
  return (
    <Card title="My Card">
      <p>This content is passed as children</p>
    </Card>
  );
}

Welcome

👋 This is card content passed as children

Features

  • Reusable components
  • Flexible layouts
  • Clean code

Code Snippet

const Component = ({ children }) => children
9

Common Patterns

1Default Props
default-props.jsx
function Button({ text = "Click me", color = "blue" }) {
  return <button style={{ background: color }}>{text}</button>;
}

// Usage: Props are optional
<Button />  // Uses defaults
<Button text="Submit" color="green" />  // Custom props
2Handling Forms
form-handling.jsx
const [formData, setFormData] = useState({
  name: "",
  email: "",
  message: ""
});

const handleChange = (e) => {
  setFormData({
    ...formData,
    [e.target.name]: e.target.value
  });
};

const handleSubmit = (e) => {
  e.preventDefault();
  console.log(formData);
  // Send to server...
};
3Toggling State
toggle.jsx
const [isOpen, setIsOpen] = useState(false);

return (
  <>
    <button onClick={() => setIsOpen(!isOpen)}>
      {isOpen ? "Close" : "Open"}
    </button>
    {isOpen && <div>Content is visible</div>}
  </>
);
10

React Hooks Overview

Hooks are special functions that let you "hook into" React features. The most common hooks are:

HookPurposeExample
useStateAdd state to componentsconst [count, setCount] = useState(0)
useEffectSide effects & cleanupuseEffect(() => {...}, [])
useContextGlobal stateconst theme = useContext(ThemeContext)
useReducerComplex state logicconst [state, dispatch] = useReducer(...)
useRefDirect DOM accessconst inputRef = useRef()
11

Best Practices

Keep components small: One responsibility per component
Use meaningful names: UserCard not Card, handleSubmit not onClick
Props vs State: Use props for data from parent, state for component's own data
Don't mutate state: Always use setter functions
Avoid inline functions: Define handlers outside JSX for performance
Use key prop: When rendering lists, always provide unique keys
12

Quick Reference Table

ConceptExampleWhen to Use
useStateconst [x, setX] = useState(0)Component's own data
Props<Card title="...">Pass data to child
onClick<button onClick={...}>Handle clicks
onChange<input onChange={...}>Handle input changes
Ternary{x ? <A /> : <B />}Show/hide based on condition
Logical AND{x && <B />}Show only if true
.map(){items.map(item => ...)}Render lists
children<Card>{content}</Card>Pass content to component
13

Common Mistakes to Avoid

❌ Mistake 1: Mutating state directly
mistake1.jsx
// WRONG
count += 1;
setCount(count);

// RIGHT
setCount(count + 1);
❌ Mistake 2: Calling hooks conditionally
mistake2.jsx
// WRONG
if (someCondition) {
  const [state, setState] = useState(0);
}

// RIGHT: Always call hooks at top level
const [state, setState] = useState(0);
❌ Mistake 3: Forgetting keys in lists
mistake3.jsx
// WRONG
{items.map((item, index) => (
  <li key={index}>{item}</li>  // Index keys are bad
))}

// RIGHT
{items.map(item => (
  <li key={item.id}>{item.name}</li>  // Use unique ID
))}
14

What's Next?

🚀 Learning Path Forward:
  1. 1. React Lists: Render and manipulate lists dynamically
  2. 2. React Hooks: useEffect, useContext, useReducer, Custom Hooks
  3. 3. API Integration: Fetch data from servers with useEffect
  4. 4. Component Patterns: Higher-Order Components, Render Props, Custom Hooks
  5. 5. State Management: Context API, Redux, Zustand for complex apps
  6. 6. Testing: React Testing Library, Jest for reliable code
  7. 7. Performance: React.memo, Code Splitting, Lazy Loading

Build projects! 🚀 The best way to learn React is by building real apps. Start small (todo list, weather app) and gradually increase complexity!

About the Author

TG

Thirdy Gayares

Passionate developer creating custom solutions for everyone. I specialize in building user-friendly tools that solve real-world problems while maintaining the highest standards of security and privacy.