What is a hook?

Hooks are special functions that are only available while React is rendering. They let you “hook into” different React features.

useState Hook - Managing Component State

The useState Hook provides two things:

  1. state variable to retain the data between renders.
  2. state setter function to update the variable and trigger React to render the component again.

useEffect Hook - Handling side effects

It is a fundamental hook. It allows you to perform side effects in your component. These are the actions that occur outside the normal flow of the component’s render. This includes things like fetching data. for example let’s say you want to fetch data only when the component mounts, you can put a fetch request in useEffect.

The useEffect takes two arguments one is the code to side effect and the other is an optional array of dependences that determines when the side effect should run. If the array is empty side effect code only runs when the element mounts on the page.

Example 1: Running on Every Render

useEffect(() => {
  console.log("This runs after every render");
});

Example 2: Running Only on Mount ([])

useEffect(() => {
  console.log("Runs once when the component mounts");

  return () => console.log("Runs on unmount (cleanup)");
}, []);

Example 3: Running When a Dependency Changes ([count])

useEffect(() => {
  console.log("Runs when count changes");
}, [count]);

useRef – DOM Access & Persistent Values