React Cheatsheet
10xdev.blog/cheatsheets
# 1. Core Concepts
// 1. Components: Reusable UI building blocks.
// This is a functional component.
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

// 2. JSX: A syntax extension for JavaScript. It looks like HTML.
const element = <h1>Hello, world!</h1>;

// 3. Props (Properties): How components receive data. They are read-only.
// Usage: <Welcome name="Alice" />

// 4. State: Data that a component manages. When state changes,
// React re-renders the component. Use the `useState` hook.
import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  // ...
}
# 2. State & Effect Hooks
import React, { useState, useEffect } from 'react';

function Timer() {
  // useState: Manages state in a functional component.
  // Returns a stateful value and a function to update it.
  const [count, setCount] = useState(0);

  // useEffect: Performs side effects.
  // Runs after every render by default.
  // The empty dependency array `[]` means it runs only once after the initial render.
  useEffect(() => {
    // Example: Fetching data or setting up a subscription
    const timerId = setInterval(() => {
      console.log('Tick');
    }, 1000);

    // Cleanup function: runs when the component unmounts
    return () => {
      clearInterval(timerId);
    };
  }, []); // <-- Dependency array

  return <h1>{count}</h1>;
}
# 3. Context & Ref Hooks
import React, { useContext, useRef, createContext } from 'react';

// useContext: Access a value from a Context provider without prop drilling.
const ThemeContext = createContext('light');

function ThemedButton() {
  const theme = useContext(ThemeContext);
  return <button>I am a {theme} button</button>;
}

// App component would have <ThemeContext.Provider value="dark">
// to provide the context value.

// useRef: Accesses DOM nodes or persists a mutable value across renders.
function TextInputWithFocus() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}
# 4. Conditional Rendering
function Greeting({ isLoggedIn }) {
  // Using if/else
  if (isLoggedIn) {
    return <h1>Welcome back!</h1>;
  }
  return <h1>Please sign up.</h1>;
}

function Mailbox({ unreadMessages }) {
  return (
    <div>
      <h1>Hello!</h1>
      {/* Using && operator */}
      {unreadMessages.length > 0 &&
        <h2>
          You have {unreadMessages.length} unread messages.
        </h2>
      }
    </div>
  );
}

function LoginButton({ isLoggedIn }) {
  // Using ternary operator
  return (
    isLoggedIn
      ? <button>Logout</button>
      : <button>Login</button>
  );
}
# 5. Lists & Keys
function TodoList({ todos }) {
  // `key` is a special string attribute you need to include when
  // creating lists of elements. Keys help React identify which
  // items have changed, are added, or are removed.
  const listItems = todos.map((todo) =>
    <li key={todo.id}>
      {todo.text}
    </li>
  );
  return <ul>{listItems}</ul>;
}

const myTodos = [
  { id: 'a', text: 'Learn React' },
  { id: 'b', text: 'Build a project' }
];
// Usage: <TodoList todos={myTodos} />
# 6. Event Handling
function ActionButton() {
  function handleClick(e) {
    e.preventDefault(); // Prevent default browser action
    console.log('The button was clicked.');
  }

  return (
    <button onClick={handleClick}>
      Click me
    </button>
  );
}

function Toggle() {
  const [isToggleOn, setIsToggleOn] = useState(true);

  // To update state, you must call the setter function
  const handleClick = () => {
    setIsToggleOn(prevState => !prevState);
  };

  return (
    <button onClick={handleClick}>
      {isToggleOn ? 'ON' : 'OFF'}
    </button>
  );
}
# 7. Create React App
# 1. Create a new React application
npx create-react-app my-app

# 2. Navigate into your new project
cd my-app

# 3. Start the development server
npm start

# 4. Build the application for production
npm run build

# 5. Run the project's tests
npm test
master* 0 0