Skip to content
Go back

React notes

React hooks

Some react hooks I’ve jotted down.

useEffect

The purpose is to run side effects in React components. A side effect is anything outside of rendering: API calls, subscriptions, timers, DOM manipulation.

userRef

Holds a mutable value that survives renders.

React Component Lifecycle

Functional components with hooks.

Mounting (component appears)

├─ useState initializes state
├─ useRef initializes refs
├─ useEffect(() => {}, [])   runs after first render (like componentDidMount)

Updating (state/props change)

├─ render with new props/state
├─ useEffect(() => {}, [deps])   runs when dependencies change

Unmounting (component removed)

├─ cleanup function from useEffect(() => return cleanup, [...]) runs

Data Flow

Parent Component (state)

├─ passes props

Child Component (can render UI, call callbacks)

├─ can call parent's setter via prop callback ↑

Mounting

When the component is created/rendered for the first time

Pattern: load data from API when the component is mounted.

function ImageLoader({ src }: { src: string }) {
  const [img, setImg] = useState<HTMLImageElement | null>(null);

  useEffect(() => {
    const image = new Image();
    image.src = src;
    image.onload = () => setImg(image);
  }, [src]);

  return <img src={img?.src} />;
}

Note that the dependency array will dictate when the useEffect will run. If it’s empty, it will run only first after the first render. If it is not included, it will run after every render. If it has values, it will run ONLY when any of those values update.


Share this post on:

Previous Post
Web scripting
Next Post
Compression