React Hooks CheatSheet

October 20, 2024 (4w ago)

Hey, Let's Learn About React Hooks!

1. useState

What's It For?
useState is like a magic box for storing little pieces of information, like your favorite color or the number of toy cars you have.

How To Use It?
Imagine you shout "Abracadabra!" to change anything in the box.

const [favoriteColor, setFavoriteColor] = useState("blue");

2. useEffect

What's It For?
useEffect is like your morning routine. When something happens, you react the same way every time.

How To Use It?
It's for keeping things in order, like brushing teeth every morning.

useEffect(() => {
  console.log("I run when something changes!");
}, [favoriteColor]);

3. useContext

What's It For?
useContext is like sharing your toys with all your friends without them asking where they are.

How To Use It?
Everyone knows where the toys are, thanks to this magical sharing!

const Theme = useContext(ThemeContext);

4. useReducer

What's It For?
useReducer is like a blueprint for your LEGO castle, guiding how you put each block.

How To Use It?
It's a plan that tells what to do to build something awesome!

const [state, dispatch] = useReducer(reducer, initialState);

5. useRef

What's It For?
useRef is like having a special magnifying glass you can use to remember things without changing them.

How To Use It?
It's your secret memory keeper.

const myToyRef = useRef();

6. useMemo

What's It For?
useMemo is like having a super brain that remembers things so you don't have to think too hard every time.

How To Use It?
It saves energy by recalling facts quickly.

const expensiveCalculation = useMemo(() => computeMagic(value), [value]);

7. useCallback

What's It For?
useCallback is like a robot that remembers how to do tasks so you can just tell it to start working.

How To Use It?
It's for doing the same job without a fuss.

const memoizedCallback = useCallback(() => doSomething(thing), [thing]);

If you want a PDF version here's that 👇

Download React Hooks CheatSheet