React Cheatsheet

Intro JSX Components Props State Events Hooks useEffect Forms Conditional Rendering Lists & Keys Context Refs Memoization React Router Custom Hooks Error Boundaries Performance Testing Best Practices

Intro

Intro
// Import React (v17+ doesn't require this for JSX)
import React from 'react';

// Render a component
import { createRoot } from 'react-dom/client';
createRoot(document.getElementById('root')).render();

JSX

JSX
const element = 

Hello, world!

; const name = "Alice"; const greet =

Hello, {name}!

; const list =
    {[1,2,3].map(n =>
  • {n}
  • )}
;

Components

Component
function Welcome(props) {
  return 

Hello, {props.name}!

; } const App = () => ;

Props

Props
function Button({ label, onClick }) {
  return ;
}

State

State
import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  return (
    
  );
}

Events

Event
function MyButton() {
  function handleClick() {
    alert('Button clicked!');
  }
  return ;
}

Hooks

Hook
import { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);
  return ;
}

useEffect

useEffect
import { useEffect } from 'react';

function Timer() {
  useEffect(() => {
    const id = setInterval(() => {
      console.log('Tick');
    }, 1000);
    return () => clearInterval(id);
  }, []);
  return 
Timer running...
; }

Forms

Form
import { useState } from 'react';

function MyForm() {
  const [value, setValue] = useState('');
  function handleChange(e) {
    setValue(e.target.value);
  }
  function handleSubmit(e) {
    e.preventDefault();
    alert(value);
  }
  return (
    
); }

Conditional Rendering

Conditional
function Greeting({ isLoggedIn }) {
  return isLoggedIn ? 

Welcome!

:

Please sign in

; }

Lists & Keys

List
const numbers = [1, 2, 3];
const listItems = numbers.map(n => 
  • {n}
  • );
      {listItems}

    Context

    Context
    import { createContext, useContext } from 'react';
    
    const ThemeContext = createContext('light');
    function ThemedButton() {
      const theme = useContext(ThemeContext);
      return ;
    }
    

    Refs

    Ref
    import { useRef } from 'react';
    
    function FocusInput() {
      const inputRef = useRef();
      function handleClick() {
        inputRef.current.focus();
      }
      return (
        <>
          
          
        
      );
    }
    

    Memoization

    Memo
    import { useMemo } from 'react';
    
    function Expensive({ n }) {
      const fib = useMemo(() => fibonacci(n), [n]);
      return 
    {fib}
    ; } function fibonacci(n) { if (n <= 1) return n; return fibonacci(n - 1) + fibonacci(n - 2); }

    React Router

    Router
    import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
    
    function App() {
      return (
        
          
          
            } />
            } />
          
        
      );
    }
    

    Custom Hooks

    Custom Hook
    import { useState, useEffect } from 'react';
    
    function useWindowWidth() {
      const [width, setWidth] = useState(window.innerWidth);
      useEffect(() => {
        const handleResize = () => setWidth(window.innerWidth);
        window.addEventListener('resize', handleResize);
        return () => window.removeEventListener('resize', handleResize);
      }, []);
      return width;
    }
    

    Error Boundaries

    Error
    class ErrorBoundary extends React.Component {
      constructor(props) {
        super(props);
        this.state = { hasError: false };
      }
      static getDerivedStateFromError(error) {
        return { hasError: true };
      }
      componentDidCatch(error, info) {
        // Log error
      }
      render() {
        if (this.state.hasError) {
          return 

    Something went wrong.

    ; } return this.props.children; } }

    Performance

    Performance
    import { memo, useCallback } from 'react';
    
    const MyComponent = memo(function MyComponent({ onClick }) {
      // ...
    });
    
    const handleClick = useCallback(() => {
      // ...
    }, []);
    

    Testing

    Testing
    // Using React Testing Library
    import { render, screen } from '@testing-library/react';
    import App from './App';
    
    test('renders learn react link', () => {
      render();
      const linkElement = screen.getByText(/learn react/i);
      expect(linkElement).toBeInTheDocument();
    });
    

    Best Practices

    Best
    // Use keys in lists
    
      {items.map(item =>
    • {item.name}
    • )}
    // Keep components small and focused // Use hooks for stateful logic // Avoid unnecessary re-renders // Use PropTypes or TypeScript for type safety