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 stateuseEffect(fn, deps)Side effectsuseContext(Ctx)Read context valueuseRef(val)Mutable ref (no re-render)useMemo(fn, deps)Memoize expensive valueuseCallback(fn, deps)Memoize callback functionuseReducer(fn, init)Complex state with reducerJSX 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 propsstyle={{ color: "red" }}Inline style objectclassName="card"CSS class (not class)Class lifecycle
componentDidMount()After first rendercomponentDidUpdate(pp, ps)After every updatecomponentWillUnmount()Before removalshouldComponentUpdate(np, ns)Skip re-render?componentDidCatch(err, info)Error boundary