React Hooks

Introduction to Hooks

Hooks are functions that let you “hook into” React state and lifecycle features from functional components. Introduced in React 16.8, Hooks allow you to use state and other features without writing class components.

Hooks simplify code, improve readability, and enable code reuse through custom hooks. All built-in hooks start with the word use.

Commonly Used Hooks

useState

The useState hook is used to add state to a functional component.


import { useState } from 'react';

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

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

useEffect

The useEffect hook lets you perform side effects like data fetching, subscriptions, or DOM updates.


import { useEffect } from 'react';

function Welcome() {
  useEffect(() => {
    console.log('Component mounted or updated');
  });

  return <h1>Hello!</h1>;
}
  

You can add a dependency array to control when the effect runs:


useEffect(() => {
  console.log('Runs once on mount');
}, []);
  

useRef

The useRef hook creates a reference to a DOM element or a persistent mutable value.


import { useRef } from 'react';

function InputFocus() {
  const inputRef = useRef(null);

  function focusInput() {
    inputRef.current.focus();
  }

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

Custom Hooks and Best Practices

Creating a Custom Hook

Custom hooks are functions that start with use and allow you to reuse stateful logic between components.


import { useState, useEffect } from 'react';

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    function handleResize() {
      setWidth(window.innerWidth);
    }

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return width;
}
  

Then use it in a component:


function ResponsiveComponent() {
  const width = useWindowWidth();
  return <p>Window width: {width}</p>;
}
  

Best Practices

  • Only call hooks at the top level of your components or custom hooks.
  • Never call hooks inside loops, conditions, or nested functions.
  • Prefix custom hooks with use to follow convention and enable linting tools.
  • Use the React DevTools to inspect hook state and debug more effectively.
  • Extract repeated logic into custom hooks for cleaner and DRY code.

Conclusion

Hooks revolutionized the way we write React applications by making functional components powerful and concise. Mastering useState, useEffect, useRef, and custom hooks will greatly improve your development experience. In the next post, we'll explore routing in React using React Router.

Post a Comment

0 Comments