Languages

React

Components, hooks, JSX patterns, and lifecycle at a glance.

Function component

function Hello({ name = 'World' }) {
  return <h1>Hello, {name}!</h1>
}

// Arrow shorthand
const Card = ({ title, children }) => (
  <div className="card">
    <h2>{title}</h2>
    {children}
  </div>
)

useState

const [count, setCount] = useState(0)
const [user, setUser] = useState(null)

// Functional update
setCount(c => c + 1)

// Partial object update
setUser(u => ({ ...u, name: 'Ada' }))

useEffect

// Run once on mount
useEffect(() => { fetchData() }, [])

// Run when dep changes
useEffect(() => {
  document.title = String(count)
}, [count])

// Cleanup on unmount
useEffect(() => {
  const sub = subscribe(handler)
  return () => sub.unsubscribe()
}, [])

Hooks reference

useState(init)Local state
useEffect(fn, deps)Side effects
useContext(Ctx)Read context value
useRef(val)Mutable ref (no re-render)
useMemo(fn, deps)Memoize expensive value
useCallback(fn, deps)Memoize callback function
useReducer(fn, init)Complex state with reducer

JSX patterns

{items.map(i => <Li key={i.id} />)}List rendering with key
{show && <Popup />}Short-circuit render
{ok ? <A /> : <B />}Ternary render
<Comp {...props} />Spread all props
style={{ color: "red" }}Inline style object
className="card"CSS class (not class)

Class lifecycle

componentDidMount()After first render
componentDidUpdate(pp, ps)After every update
componentWillUnmount()Before removal
shouldComponentUpdate(np, ns)Skip re-render?
componentDidCatch(err, info)Error boundary