> front-end

Hooks

Created by: Kitman Yiu

Updated at: 1 day ago

  • Definition: they provide a way to use stateful logic in functional components.
  • Benefits: n/a
  • Keywords: After React version 16.8, removed limitation functional components could not use state and lifecycle features

1. Where does it come from?

Hooks are a new feature introduced in React version 16.8, allowing the use of state and other React features in functional components.

  • Origin: Before Hooks, React's functional components couldn't use state and lifecycle features, which were only available in class components. The introduction of Hooks removed this limitation.
  • Comparison: Before Hooks, React developers had to choose between functional and class components. With Hooks, functional components gained abilities similar to class components, like state management and lifecycle control.

2. What is it?

Hooks are a set of functions that allow developers to "hook into" React state and lifecycle features within functional components.

  • Method of Solution: They offer a more concise and intuitive way to manage state and side effects without writing class components.
  • Three Key Principles:
    1. Only use Hooks at the top level, not inside loops, conditions, or nested functions.
    2. Only call Hooks from React functions, avoid calling them from regular JavaScript functions.
    3. When using Hooks for component features, focus on separation of concerns rather than lifecycle methods.

Example:

Background
Suppose you need to build a component that displays a counter, which can be incremented and decremented.
Application
Use the `useState` Hook to manage the counter's state, and the `useEffect` Hook to handle side effects after the component updates.
Code Example

    function Counter() {
        const [count, setCount] = useState(0);
    
        useEffect(() => {
            document.title = `You clicked ${count} times`;
        });
    
        return (
            <div>
                <p>You clicked {count} times</p>
                <button onClick={() => setCount(count + 1)}>Click me</button>
            </div>
        );
    }
                    

3. Where is it going?

  • Limitations: For complex state logic, Hooks may not be as intuitive as class components, especially in large projects.
  • Direction for Optimization: Continue to develop and improve the Hooks API for easier management of complex states and side effects.
  • Future Development: We may see more specialized Hooks in the future, providing more custom functionality and optimizations to meet different development needs.