All React Hooks

All React Hooks

Introduction

React Hooks have revolutionized the way we manage state and lifecycle in React components. Whether you're a seasoned React developer or just getting started, understanding and mastering React Hooks is essential for building modern, efficient, and maintainable applications. Grab a cup of coffee, and let's dive into React Hooks mastery!

1. useState

useState is perhaps the most fundamental React Hook, allowing you to add state to functional components. Here's a quick overview:

  • Use Case: Managing local component state.

  • Syntax:

      const [state, setState] = useState(initialState);
    
  • Example:

      import React, { useState } from 'react';
    
      function Counter() {
        const [count, setCount] = useState(0);
    
        return (
          <div>
            <p>Count: {count}</p>
            <button onClick={() => setCount(count + 1)}>Increment</button>
          </div>
        );
      }
    
      export default Counter;
    

2. useEffect

useEffect enables you to perform side effects in functional components, such as data fetching, subscriptions, or manually managing DOM elements. Key points to remember:

  • Use Case: Handling side effects in functional components.

  • Syntax:

      useEffect(() => {
        // Side effect code here
        return () => {
          // Cleanup code here (optional)
        };
      }, [dependencies]);
    
  • Example:

      import React, { useState, useEffect } from 'react';
    
      function Timer() {
        const [seconds, setSeconds] = useState(0);
    
        useEffect(() => {
          const interval = setInterval(() => {
            setSeconds(seconds => seconds + 1);
          }, 1000);
    
          return () => clearInterval(interval);
        }, []);
    
        return <p>Seconds: {seconds}</p>;
      }
    
      export default Timer;
    

3. useContext

useContext provides a way to consume context values in functional components without nesting. Here's how you can use it:

  • Use Case: Accessing context values in functional components.

  • Syntax:

      const value = useContext(MyContext);
    
  • Example:

      import React, { useContext } from 'react';
    
      const ThemeContext = React.createContext('light');
    
      function ThemedButton() {
        const theme = useContext(ThemeContext);
    
        return <button style={{ background: theme }}>Themed Button</button>;
      }
    
      export default ThemedButton;
    

4. UseReducer

useReducer is an alternative to useState for managing complex state logic in functional components. It's especially useful when state transitions depend on the previous state. Here's how it works:

  • Use Case: Managing complex state logic.

  • Syntax:

      const [state, dispatch] = useReducer(reducer, initialState);
    
  • 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:
            throw new Error();
        }
      }
    
      function 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>
        );
      }
    
      export default Counter;
    

5. useCallback

useCallback memoizes functions to prevent unnecessary re-renders in functional components. It's useful for optimizing performance when passing callbacks to child components. Key points:

  • Use Case: Memoizing functions to prevent unnecessary re-renders.

  • Syntax:

      const memoizedCallback = useCallback(() => {
        // Function body
      }, [dependencies]);
    
  • Example:

      import React, { useState, useCallback } from 'react';
    
      function Parent() {
        const [count, setCount] = useState(0);
    
        const handleClick = useCallback(() => {
          setCount(count + 1);
        }, [count]);
    
        return (
          <div>
            <p>Count: {count}</p>
            <Child handleClick={handleClick} />
          </div>
        );
      }
    
      function Child({ handleClick }) {
        return <button onClick={handleClick}>Increment</button>;
      }
    
      export default Parent;
    

6. useMemo

useMemo memoizes expensive computations in functional components, optimizing performance by avoiding unnecessary recalculations. Here's how to use it:

  • Use Case: Memoizing expensive computations.

  • Syntax:

      const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
    
  • Example:

      import React, { useMemo } from 'react';
    
      function ExpensiveComponent({ a, b }) {
        const result = useMemo(() => {
          // Expensive computation
          return a * b;
        }, [a, b]);
    
        return <p>Result: {result}</p>;
      }
    
      export default ExpensiveComponent;
    

Conclusion

And that is all to it. Congratulations! You've now mastered React Hooks. Happy coding!