Mastering React Hooks: Your Ultimate Guide with Examples 🎯

tirthorajmondal

Tirtho Raj Mondal

Posted on November 29, 2024

Mastering React Hooks: Your Ultimate Guide with Examples 🎯

React Hooks are a game-changer for modern web development, empowering developers to build cleaner and more functional code. Whether you're a React newbie or looking to sharpen your skills, here's a breakdown of the most essential React Hooksβ€”complete with examples!

πŸ”‘ 1. useState

Manage dynamic state in functional components.

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

function increment() {
  setCount(count + 1);
}

return (
  <div>
    <p>Count: {count}</p>
    <button onClick={increment}>Increment</button>
  </div>
);
Enter fullscreen mode Exit fullscreen mode

Use Case: Toggle states, counters, or inputs.

πŸ”‘ 2. useEffect
Handle side effects like fetching data or interacting with the DOM.

useEffect(() => {
  document.title = `Count: ${count}`;
}, [count]); // Only runs when count changes
Enter fullscreen mode Exit fullscreen mode

Use Case: Data fetching, subscriptions, or cleanup.

πŸ”‘ 3. useContext

Skip prop drilling and share data across components.

const ThemeContext = React.createContext('light');

function App() {
  const theme = useContext(ThemeContext);
  return <div style={{ background: theme === 'dark' ? '#333' : '#fff' }}>Hello!</div>;
}
Enter fullscreen mode Exit fullscreen mode

Use Case: Global data like themes or authentication.

πŸ”‘ 4. useReducer
Manage complex state transitions.

const reducer = (state, action) => {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
};

const [state, dispatch] = useReducer(reducer, { count: 0 });
Enter fullscreen mode Exit fullscreen mode

Use Case: State-heavy components like forms or complex UIs.


πŸ”‘ 5. useRef

Access a mutable reference for DOM elements or persisted variables.

const inputRef = useRef();

return (
  <div>
    <input ref={inputRef} />
    <button onClick={() => inputRef.current.focus()}>Focus</button>
  </div>
);
Enter fullscreen mode Exit fullscreen mode

Use Case: DOM access, timers, or animations.

πŸ”‘ 6. useMemo

Optimize expensive calculations by memoizing their results.

const doubledValue = useMemo(() => number * 2, [number]);
Enter fullscreen mode Exit fullscreen mode

Use Case: Avoid performance bottlenecks during re-renders.

πŸ”‘ 7. useCallback

Memoize functions to prevent unnecessary re-creations.

const handleClick = useCallback(() => {
  console.log('Clicked!');
}, []);
Enter fullscreen mode Exit fullscreen mode

Use Case: Stable functions in child components or event handlers.

πŸ”‘ 8. Custom Hooks
Reuse your logic across multiple components.

function useFetch(url) {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch(url).then(response => response.json()).then(setData);
  }, [url]);

  return data;
}

const data = useFetch('https://api.example.com');
Enter fullscreen mode Exit fullscreen mode

Use Case: DRY code for fetching, authentication, or animations.

🌟 Why Hooks Are a Game-Changer
Hooks simplify React code, reduce boilerplate, and let you focus on building functional, reusable, and maintainable components. Whether you're managing state or optimizing performance, these hooks are your toolbox!

What’s your favorite React Hook?
Let me know in the comments! And if you found this guide useful, follow me here or connect with me on my page: (https://dev.to/tirthorajmondal) πŸš€

πŸ’– πŸ’ͺ πŸ™… 🚩
tirthorajmondal
Tirtho Raj Mondal

Posted on November 29, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related