Exploring React Hooks: A Guide with Examples

Exploring React Hooks: A Guide with Examples

Development

🌟 Exploring React Hooks: A Guide with Examples 🎉

React hooks are 🔗 functions that let you "hook into" React state and lifecycle features from function components. Since their debut in React 16.8, hooks have revolutionized how we write components, making it easier to manage state, side effects, context, and more!

In this guide, we'll dive into React's most popular hooks with đŸŽ¯ examples and explain how they simplify your coding life. Let's get started! đŸ’ģ🎈


đŸ› ī¸ 1. useState – Add State to Functional Components đŸ–‹ī¸

🌀 Purpose:

useState 🧰 adds state to functional components. It returns an array with two items:

  1. The current state value.
  2. A function to update the state.

âœī¸ Code Example:

import React, { useState } from 'react';

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

  const increment = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count} đŸ”ĸ</p>
      <button onClick={increment}>➕ Increment</button>
    </div>
  );
};

💡 What's Happening?

The count is our state, and we use setCount to update it when the button is clicked. Super simple! 😎


⏰ 2. useEffect – Handle Side Effects 🔄

🌀 Purpose:

useEffect helps you perform side effects like:

  • Fetching data 📡
  • Subscribing to events 🔔
  • Updating the DOM manually âœī¸

âœī¸ Code Example:

import React, { useState, useEffect } from 'react';

const Timer = () => {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds((prev) => prev + 1);
    }, 1000);

    return () => clearInterval(interval); // Cleanup âšī¸
  }, []); // Empty dependency array means it runs once 🕒

  return <p>Timer: {seconds} âŗ seconds</p>;
};

💡 What's Happening?

  • The timer 🕒 increments every second.
  • Cleanup (clearInterval) ensures no memory leaks! 💧

🎨 3. useContext – Simplify Prop Drilling 🎁

🌀 Purpose:

useContext 🔌 accesses context values directly, skipping the need for prop drilling.

âœī¸ Code Example:

import React, { createContext, useContext } from 'react';

const ThemeContext = createContext('light');

const ThemedComponent = () => {
  const theme = useContext(ThemeContext);

  return <div>🎨 The current theme is {theme}.</div>;
};

const App = () => (
  <ThemeContext.Provider value="dark">
    <ThemedComponent />
  </ThemeContext.Provider>
);

💡 What's Happening?

No more prop passing! đŸ›Ąī¸ useContext grabs the theme (dark) from the ThemeContext provider.


🤖 4. useReducer – Manage Complex State âš™ī¸

🌀 Purpose:

When state logic gets 🔀 complex, useReducer can replace useState for better clarity.

âœī¸ Code Example:

import React, { useReducer } from 'react';

const initialState = { count: 0 };

function reducer(state, action) {
  switch (action.type) {
    case 'increment': return { count: state.count + 1 };
    case 'decrement': return { count: state.count - 1 };
    default: return state;
  }
}

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

  return (
    <div>
      <p>Count: {state.count} đŸ”ĸ</p>
      <button onClick={() => dispatch({ type: 'increment' })}>➕ Increment</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>➖ Decrement</button>
    </div>
  );
};

💡 What's Happening?

  • dispatch 🚀 triggers actions (increment or decrement) to modify state.
  • Perfect for multi-step or complex updates! đŸ› ī¸

đŸŽ¯ 5. useRef – Access DOM Directly 📍

🌀 Purpose:

useRef is like a magical portal 🌀 to interact with DOM elements without causing re-renders.

âœī¸ Code Example:

import React, { useRef } from 'react';

const FocusInput = () => {
  const inputRef = useRef();

  const focusInput = () => {
    inputRef.current.focus(); // DOM magic ✨
  };

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={focusInput}>🔍 Focus Input</button>
    </div>
  );
};

💡 What's Happening?

  • Clicking the button calls focusInput to focus the text input.
  • Handy for forms, animations, or DOM manipulation. đŸ§™â€â™‚ī¸

🚀 6. useMemo – Optimize Expensive Calculations 🔍

🌀 Purpose:

useMemo 🧠 avoids re-computing expensive calculations unless dependencies change.

âœī¸ Code Example:

import React, { useMemo, useState } from 'react';

const ExpensiveCalculation = ({ num }) => {
  const result = useMemo(() => {
    console.log('Calculating... 🤔');
    return num * 2;
  }, [num]);

  return <p>Result: {result} 💡</p>;
};

const App = () => {
  const [num, setNum] = useState(0);

  return (
    <div>
      <button onClick={() => setNum(num + 1)}>➕ Increment</button>
      <ExpensiveCalculation num={num} />
    </div>
  );
};

đŸ’Ŧ 7. useCallback – Memoize Functions 🔗

🌀 Purpose:

useCallback avoids recreating functions unnecessarily, optimizing component re-renders.

âœī¸ Code Example:

import React, { useState, useCallback } from 'react';

const Button = React.memo(({ onClick }) => {
  console.log('Button rendered'); // Only re-renders when onClick changes
  return <button onClick={onClick}>Click me</button>;
});

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

  const increment = useCallback(() => setCount(count + 1), [count]);

  return (
    <div>
      <p>Count: {count} đŸ”ĸ</p>
      <Button onClick={increment} />
    </div>
  );
};

đŸŽĨ 8. useLayoutEffect – Read & React to Layout đŸ–ŧī¸

🌀 Purpose:

useLayoutEffect runs synchronously after DOM mutations, before the browser paints.

âœī¸ Code Example:

import React, { useLayoutEffect, useState } from 'react';

const LayoutEffectExample = () => {
  const [width, setWidth] = useState(0);

  useLayoutEffect(() => {
    setWidth(window.innerWidth);
  }, []);

  return <p>Window width: {width} đŸ–Ĩī¸</p>;
};

🎉 Conclusion

React hooks are a game-changer! From managing state with useState 🌀 to optimizing performance with useMemo ⚡, hooks make React functional components powerful and elegant. Dive into these hooks and elevate your React skills to the next level! đŸ’Ē✨

Happy coding! đŸ’ģ🎈