DEV Community

Huzaifa shoaib
Huzaifa shoaib

Posted on

๐Ÿš€ Understanding React Hooks in Depth

โ€œThe best way to understand something is to break it down to its simplest form.โ€

React Hooks were introduced in React 16.8, changing how we write components forever. They allow you to use state and lifecycle features without writing a class. Letโ€™s explore them in a beginner-friendly, practical way.

๐Ÿง  Why Hooks?

Before Hooks, you had to use class components to manage state and side effects. With Hooks, functional components became just as powerful โ€” and a lot cleaner.

โ€œSimplicity does not precede complexity, but follows it.โ€ โ€” Alan Perlis

๐Ÿ”ง Commonly Used Hooks

1. useState() โ€” State in Functional Components

const [count, setCount] = useState(0);

It returns a stateful value and a function to update it.

2. useEffect() โ€” Side Effects (e.g., API calls, DOM updates)

useEffect(() => {
  console.log("Component mounted or updated");
}, [dependency]);

Think of it as componentDidMount, componentDidUpdate, and componentWillUnmount in one.

3. useContext() โ€” Access Global Data (without prop drilling)

const theme = useContext(ThemeContext);

It helps you consume values from React Context easily.

4. useRef() โ€” Mutable Values That Persist

const inputRef = useRef(null);

Itโ€™s useful for accessing DOM nodes or keeping mutable variables that donโ€™t trigger re-renders.

5. useReducer() โ€” Advanced State Management

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

Great for complex state logic, often used with global state tools.

๐ŸŽฏ Custom Hooks โ€” Reusable Logic

You can build your own hooks to reuse logic between components.

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);
  useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);
  return width;
}

โ€œDonโ€™t Repeat Yourself โ€” make a custom hook instead.โ€ โ€” Every React Dev

โœ… Final Thoughts

React Hooks make code cleaner, reusable, and easier to reason about.

Once you master them, your productivity as a React developer skyrockets ๐Ÿš€

โ€œHooks are not magic. Theyโ€™re just functions โ€” but really powerful ones.โ€

Top comments (0)