Cool React Hooks cheat sheet
Ian Oliv / December 27, 2021
2 min read • ––– views
Cool React Hooks cheat sheet
- useState
- useEffect
- useContext
- useReducer
- useCallback
- useRef
- useImperativeHandle
useState
const [count, setCount] = useState(0);
above we have two variables count and setCount and we are using useState to create a state management hook.
useEffect
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
This is a good place to set up a timer. You can also use it to fetch data from an API
useContext
// useContext example
const ThemeContext = React.createContext('light');
function Toolbar(props) {
return (
<div>
<ThemedButton />
</div>
);
}
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button style={{ background: theme }}>Hover me!</button>;
}
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
this is a example of useContext. That is how we can use context in react and use it in our components.
useReducer
const [count, dispatch] = useReducer(reducer, 0);
function reducer(state, action) {
switch (action) {
case 'increment':
return state + 1;
case 'decrement':
return state - 1;
default:
throw new Error();
}
}
This is a good example of how to use useReducer.
useCallback
const [count, setCount] = useState(0);
const increment = useCallback(() => setCount(count + 1), [count]);
const decrement = useCallback(() => setCount(count - 1), [count]);
This is useful for memoizing expensive functions.
useRef
function FocusInput() {
const inputRef = useRef();
useEffect(() => {
inputRef.current.focus();
}, []);
return <input ref={inputRef} />;
}
This hook returns a mutable ref object whose .current
property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.
useImperativeHandle
function FancyInput(props, ref) {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
},
}));
const CountContext = React.createContext();
This is a great way to pass methods from a parent component to a child component.