yogeshkathayat.dev
Back to Blog
React
JavaScript
Web Development

Mastering React Hooks

React Hooks have revolutionized how we write React components. In this guide, we'll explore some advanced patterns.

The useEffect Hook

The useEffect hook lets you perform side effects in function components.

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

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

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, [count]);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Custom Hooks

You can also create your own hooks to reuse stateful logic.

import { useState, useEffect } from 'react';

function useWindowSize() {
  const [size, setSize] = useState([0, 0]);

  useEffect(() => {
    function updateSize() {
      setSize([window.innerWidth, window.innerHeight]);
    }
    window.addEventListener('resize', updateSize);
    updateSize();
    return () => window.removeEventListener('resize', updateSize);
  }, []);

  return size;
}

Images in Markdown

Here is an example of how you can include images in your markdown posts.

React Logo

"Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class."

Conclusion

Hooks provide a more direct API to the React concepts you already know.