React Hook Stuff Flashcards
(11 cards)
what makes a function a hook?
A function becomes a hook when:
It uses other hooks inside it, such as:
useState
useEffect
useRef
useContext
etc.
It starts with the word use — this is required by React’s rules so that the linter can enforce the Rules of Hooks.
What are the two rules for Hooks
According to React’s official rules:
- Only call hooks at the top level.
Never inside conditions, loops, or nested functions - Only call hooks from React functions.
This means from a React component or another hook
“Only call hooks from React functions.”
This means…..
A. You can call hooks inside a React component
B. You can call hooks inside a custom hook
C. You CANNOT call hooks from:
* Regular JavaScript functions
- Class components
- Conditional blocks (if, for, etc.)
- Event handlers or callbacks (directly)
What is a Lazy Initializer in useState?
React’s useState can accept either:
A value: directly used as the initial state.
A function: which React will call once (lazily) to compute the initial value.
Lazy Initializer Form (what your line uses):
useState(() => cache.get(url) ?? null);
React will call the function only on the first render to get the initial state.
It’s useful when computing the value is expensive or optional, such as reading from a cache, localStorage, or doing a calculation.
Prevents the computation from happening on every render.
WRONG Eager Evaluation (non-lazy form):
useState(cache.get(url) ?? null);
In this version, cache.get(url) runs immediately, whether or not React actually needs to initialize state right now.
On every render, this code is evaluated—but useState will ignore it after the first render.
This can lead to unnecessary computation if cache.get(url) is expensive, or if it’s not needed (e.g. in server-side rendering scenarios).
In the useEffect, when does a return run?
It runs to cleanup before the component unmounts or before the effect runs again. (When dependencies change.)
What does the return inside a useEffect do?
- Defines a cleanup function.
- It only runs when the component un-mounts or before the effect re-runs
- It’s not a normal return like a function.
When to use a return function in the useEffect?
- When canceling API requests
- Clearing timeouts.
- unsubscribing to listeners.
Definition of useEffect
Action to let your code run after react has updated the screen.
Like Saying
“Hey after you paint everything on the page, I need to run some side work like fetching data, setting up timers etc”
When should you use useEffect?
- When fetching api data after the page loads
- Listening to scroll events
- Set Time Intervals
- Cleaning up components