Cheatsheet

React

Components

Function componentCopy
function Welcome({ name }) {
  return <h1>Hello, {name}</h1>;
}
iThe standard way to build a piece of interface today: a function that takes some input and returns what should appear on screen.
Arrow function componentCopy
const Welcome = ({ name }) => (
  <h1>Hello, {name}</h1>
);
iThe exact same idea as a function component, just written in a shorter style — common for small pieces of interface.
Rendering to the DOMCopy
import { createRoot } from 'react-dom/client';

createRoot(document.getElementById('root')).render(<App />);
iThe code that actually puts your React app onto the page, inside a specific spot in the HTML.
Multiple elements (Fragment)Copy
function List() {
  return (
    <>
      <li>One</li>
      <li>Two</li>
    </>
  );
}
iA component can only return one thing — this lets you group several elements together without adding an extra wrapper around them.

State & Effects (Hooks)

useStateCopy
const [count, setCount] = useState(0);

setCount(count + 1);
setCount(c => c + 1); // functional update
iLets a component remember and update a value over time, like a counter or whether a menu is currently open.
useEffectCopy
useEffect(() => {
  document.title = `Count: ${count}`;
}, [count]);
iRuns some code after the component appears on screen, and again whenever specific values change — often used for things like loading data.
useEffect cleanupCopy
useEffect(() => {
  const id = setInterval(tick, 1000);
  return () => clearInterval(id);
}, []);
iLets you clean up after an effect (like stopping a timer) right before it runs again, or when the component disappears from the page.
useReducerCopy
function reducer(state, action) {
  switch (action.type) {
    case 'increment': return { count: state.count + 1 };
    default: return state;
  }
}

const [state, dispatch] = useReducer(reducer, { count: 0 });
dispatch({ type: 'increment' });
iAn alternative to useState for when the way a value updates is more complicated than a simple set — all updates go through one central function.

Other Hooks

useContextCopy
const theme = useContext(ThemeContext);
iLets a component read a shared value, like the current theme, without it being passed down by hand through every component in between.
useRefCopy
const inputRef = useRef(null);

useEffect(() => {
  inputRef.current.focus();
}, []);

<input ref={inputRef} />
iLets you keep hold of a value — often a reference to something on screen, like an input box — without it causing the component to re-render.
useMemoCopy
const total = useMemo(() => expensiveCalc(items), [items]);
iRemembers the result of a slow calculation so it doesn't have to be redone every time, unless its inputs actually change.
useCallbackCopy
const handleClick = useCallback(() => {
  doSomething(id);
}, [id]);
iRemembers a function so it isn't recreated on every render, which can help avoid extra unnecessary work elsewhere.

Custom Hooks

Extracting reusable logicCopy
function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    const onResize = () => setWidth(window.innerWidth);
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);

  return width;
}
iYour own reusable bit of logic, built out of the built-in hooks, that you can share between different components.

Events

Inline handlerCopy
<button onClick={() => setCount(count + 1)}>+</button>
iRuns some code when a visitor clicks a button — you give it a function to run, not the result of running it.
Handler with argumentCopy
function handleClick(id) {
  return () => doSomething(id);
}

<button onClick={handleClick(item.id)}>Go</button>
iShows how to pass extra information along with a click, by wrapping your function so it knows what to act on.
Form inputCopy
<input value={text} onChange={e => setText(e.target.value)} />
iKeeps a text box in sync with your component's own data — whatever the visitor types updates your stored value right away.

Conditionals & Lists

Short-circuit renderingCopy
{isLoggedIn && <p>Welcome back!</p>}
iShows something on screen only if a condition is true; shows nothing at all if it's false.
Ternary renderingCopy
{isLoggedIn ? <Dashboard /> : <Login />}
iPicks between two different things to show, based on a yes/no condition, all in one line.
Rendering a listCopy
<ul>
  {items.map(item => (
    <li key={item.id}>{item.name}</li>
  ))}
</ul>
iTurns a list of data into a list of visual items on screen. Each one needs a unique "key" so React can keep track of them properly.

Props

Destructuring propsCopy
function Card({ title, children, ...rest }) {
  return (
    <div {...rest}>
      <h2>{title}</h2>
      {children}
    </div>
  );
}
iPulls out the specific pieces of input a component needs by name, instead of referring to the whole input bundle every time.
Default propsCopy
function Button({ variant = 'primary' }) {
  return <button className={variant}>Click</button>;
}
iGives a component input a fallback value to use if nothing was provided for it.
children propCopy
function Panel({ children }) {
  return <div className="panel">{children}</div>;
}

<Panel><p>Nested content</p></Panel>
iWhatever you place between a component's opening and closing tags gets passed to it automatically, ready to be displayed wherever it wants.

Context

Create & provideCopy
const ThemeContext = createContext('light');

<ThemeContext.Provider value="dark">
  <App />
</ThemeContext.Provider>
iSets up a shared value, like a theme, that any component further down the page structure can access.
Consume with useContextCopy
function Button() {
  const theme = useContext(ThemeContext);
  return <button className={theme}>Click</button>;
}
iReads that shared value from inside any nested component, without it needing to be passed down by hand.

Refs, Portals & Fragments

forwardRefCopy
const Input = forwardRef((props, ref) => (
  <input ref={ref} {...props} />
));
iLets a parent component reach directly into a child component and grab hold of one of its actual on-screen elements.
PortalsCopy
createPortal(<Modal />, document.body)
iRenders part of your interface, like a popup, into a completely different spot on the page than where the component actually sits in your code.
Keyed FragmentCopy
<React.Fragment key={item.id}>
  <dt>{item.term}</dt>
  <dd>{item.desc}</dd>
</React.Fragment>
iThe longer way to group elements together while also giving that group a unique key, needed when it's part of a list.

Class Components (legacy)

Basic class componentCopy
class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}
iAn older style of writing a component. Still works today, but function components (shown earlier) are the modern default.
State & setStateCopy
class Counter extends React.Component {
  state = { count: 0 };

  increment = () => {
    this.setState(s => ({ count: s.count + 1 }));
  };

  render() {
    return <button onClick={this.increment}>{this.state.count}</button>;
  }
}
iHow the older, class-based components keep track of and update their own data — the equivalent of useState.

PropTypes

Type validationCopy
import PropTypes from 'prop-types';

MyComponent.propTypes = {
  name: PropTypes.string.isRequired,
  age: PropTypes.number,
  onSave: PropTypes.func,
};
iLets you declare what kind of input each part of a component expects, so you get a warning during development if the wrong thing gets passed in.
What is this Cheatsheet?

A quick reference for modern CSS, SASS, SCSS, Pug, and React syntax. Switch between tabs to browse selectors, layout, hooks, and more. Click any snippet to copy it, or hover the info icon for an explanation.