React Hooks Cheatsheet
A quick reference for the most common React Hooks, their purpose, and basic usage with examples.
useStateThe useState hook allows you to add state to functional components. It returns a stateful value and a function to update it.
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}useEffectThe useEffect hook lets you perform side effects in function components. It's a close replacement for componentDidMount, componentDidUpdate, and componentWillUnmount.
import React, { useState, useEffect } from 'react';
function DocumentTitleUpdater() {
const [count, setCount] = useState(0);
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes
return (
<button onClick={() => setCount(count + 1)}>
Update Title
</button>
);
}useContextAccepts a context object (the value returned from React.createContext) and returns the current context value for that context.
const ThemeContext = React.createContext('light');
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button className={theme}>I am a {theme} button</button>;
}
function App() {
return (
<ThemeContext.Provider value="dark">
<ThemedButton />
</ThemeContext.Provider>
);
}