React Hook이 무엇인가요? 🎣

목차


  • Introduction
  • What are Hooks?
  • useState
  • useEffect
  • Rules of Hooks
  • Building your own Hooks
  • Additional Hooks and API Reference
  • Conclusion

  • 소개

    React is a free and open-source front-end JavaScript library for UI components, maintained by Facebook and a group of individual developers. However it's used, React is only concerned with state management and rendering that state to the DOM, initially through React state and lifecycle methods.

    But that all changed when React 16.8 was introduced, its new addition of Hooks allow the use of state and other React features without writing a class. Hooks were developed to solve a bunch of unconnected problems in React. Some of the problems (are not limited too) include:

  • It’s hard to reuse stateful logic between components
  • Complex components become hard to understand
  • Classes confuse both people and machines

  • 후크란 무엇입니까?

    Hooks are simply just functions that let you “hook into” React state and lifecycle features. Unlike lifecycle methods, Hooks don’t work inside classes. Which can make working with them super flexible, since they let you use lifecycle features in function components. While React provides a few built-in Hooks like useState, you can also create your own Hooks to reuse stateful behavior between components.

    useState

    This example was taken from and can be seen in the React Documentation 후크용.

    React에 익숙하다면 다음과 같이 상태가 처리되는 것을 볼 수 있습니다.

    class Example extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          count: 0
        };
      }
    
      render() {
        return (
          <div>
            <p>You clicked {this.state.count} times</p>
            <button onClick={() => this.setState({ count: this.state.count + 1 })}>
              Click me
            </button>
          </div>
        );
      }
    }
    


    그러나 React Hooks를 사용하면 다음과 같이 바뀝니다.

    // This example renders a counter. When you click the button, it increments the value:
    import React, { useState } from 'react';
    
    function Example() {
      // Declare a new state variable, which we'll call "count"
      const [count, setCount] = useState(0);
    
      return (
        <div>
          <p>You clicked {count} times</p>
          <button onClick={() => setCount(count + 1)}>
            Click me
          </button>
        </div>
      );
    }
    


    우리가 살펴볼 첫 번째 Hook은 State Hook입니다. useState는 로컬 상태를 추가하기 위해 함수 구성 요소 내부에서 호출되는 후크입니다. 일단 추가되면 React는 후크를 사용하여 현재 상태 값과 이를 업데이트하기 위한 함수라는 두 가지를 반환하여 재렌더링 사이에 이 상태를 유지합니다. 이 함수는 이벤트 핸들러와 같이 어디에서나 호출할 수 있습니다. React에 익숙하다면 이전 상태와 업데이트된 상태를 함께 병합하지 않고 클래스의 this.setState와 비교하십시오.

    "useState"는 첫 번째 렌더링 중에만 사용되는 하나의 초기 인수만 받습니다. 앞의 예에서 카운터가 0부터 시작하기 때문에 이 인수는 "0"입니다. this.state와 달리 여기서 상태는 객체일 필요가 없습니다.

    "useState"후크를 사용하여 여러 변수를 선언하는 방법을 이해할 수 있습니다here.

    useEffect

    When coding with React, you may perform data fetching, subscriptions, or manually changing the DOM. The React developers like to call these “side effects” since they affect other components, and can’t be done while rendering.

    The Effect Hook, useEffect, adds the ability to effect from, you guessed it, a function component. Similar to componentDidMount, componentDidUpdate, and componentWillUnmount in React classes, "useEffect" is unified into a single API.

    Going off the example before, after React updates the DOM, the component sets the document title:

    import React, { useState, useEffect } from 'react';
    
    function Example() {
      const [count, setCount] = useState(0);
    
      // Similar to componentDidMount and componentDidUpdate:
      useEffect(() => {
        // Update the document title using the browser API
        document.title = `You clicked ${count} times`;
      });
    
      return (
        <div>
          <p>You clicked {count} times</p>
          <button onClick={() => setCount(count + 1)}>
            Click me
          </button>
        </div>
      );
    }
    

    By calling "useEffect", you’re telling React to run the “effect” function you created after pushing changes to the DOM. Effects are declared inside the component, so they have access to props and state. By default, React runs the effects after every render, starting with the first one. Effects can also optionally specify actions to take after by returning a function. Hooks let you organize side effects in a component by what ideas are related, rather than forcing a split based on lifecycle methods.

    Unlike the lifecycle methods, componentDidMount or componentDidUpdate, effects scheduled with useEffect don’t block the browser from updating the screen. This cut back on processing time, since the majority of effects don’t need to happen synchronously, making your app feel more responsive. In a case where effects do need to occur synchronously(such as measuring the layout), there is a separate useLayoutEffect Hook with an API identical to useEffect. You can learn more about that in the Additional Hooks and API Reference 섹션.

    후크 규칙

    Despite Hooks being Javascript functions, there are still several rules they must follow in order to maintain the black magic that gives them lifecycle features.

    1. Only Call Hooks at the Top Level

      • Always use Hooks at the top level of your React function, before any early returns. This means don’t call Hooks inside loops, conditions, or nested functions. This ensures that Hooks are called in the same order each time a component renders, which allows React to correctly preserve the state of Hooks between varying useState and useEffect calls.
    2. Only Call Hooks from React Functions

      • Don’t call Hooks from regular JavaScript functions. Try the following instead:
        • Call Hooks from custom Hooks
        • Call Hooks from React function components.
    To make things easy, the React developers made this plugin 이러한 규칙을 자동으로 적용합니다. 하지만 그렇다고 해서 올바른 후크 에티켓을 아는 것을 건너뛰어야 한다는 의미는 아닙니다.

    나만의 Hook 만들기

    What if you want to go beyond just the Effect Hook? Well, there's an answer for that, build your own! By building your own Hooks, you can extract component logic into reusable functions. You may be use to doing this in React through: render props and higher-order components. But with the addition of Hooks, you can solve many of the same problems without adding more components to the tree. No one likes cluttered code!

    Think about how share logic between two JavaScript functions, you extract it into yet another function. And since components and Hooks are functions, this works for them too!

    A custom Hook is a JavaScript function whose name starts with ”use” and has the ability to call other Hooks.

    You can write custom Hooks that cover a variety of cases such as form handling, animation, timers, and much more. Don't be afraid to experiment with creating your own Hooks, because you might find yourself making a meaningful contribution to others down the line. React even provides documentation 오픈 소스 프로젝트에 기여하는 방법.

    고유한 사용자 정의 후크 작성에 대한 자세한 내용과 몇 가지 예는 사용자 정의 후크 생성에 대한 React Documentation을 참조하십시오.

    추가 리소스로 자신만의 후크를 만드는 방법을 자세히 설명하고 "useFetch"사용자 지정 후크와 같은 몇 가지 훌륭한 예제를 제공하는 또 다른 최근 블로그 게시물이 있습니다. 확인해보세요here !

    추가 후크 및 API 참조

    If you're interested in learning about the Hooks API reference, the React documentation provides a reader friendly explanation for the basic hooks :
  • useState
  • useEffect
  • useContext

  • additional Hooks은 기본 변형의 변형이거나 특정 엣지 케이스에만 필요한 것입니다. 도움이 되지만 추가 사항일 뿐이므로 바로 배우는 것에 대해 걱정하지 마십시오. 이러한 후크에는 다음이 포함됩니다.
  • useReducer
  • useCallback
  • useMemo
  • useRef
  • useImperativeHandle
  • useLayoutEffect
  • useDebugValue

  • 결론

    React is constantly changing, and programmers who are focused on developing products may not have the time to learn and use every new API released. Hooks are still fairly new, so while they may come in handy, there's no rush to adopt them into your every day practices, unless that's what your heart desires.

    Hooks were made to work side-by-side with existing code, which allows you to adopt them gradually, meaning there is no rush to migrate to Hooks. Do not feel the need to do some “big rewrite”, especially for existing, complex class components. It's a bit of a learning curve to start “thinking in Hooks”. So practice using Hooks in your unimportant work first, and once you, and anyone you're working with, feel comfortable with them, give them a go!

    Hooks were made in hopes to one day cover all existing use cases for classes, but don't worry because class components aren't going anywhere soon. If you don't believe me, I'll quote the React developers themselves,

    "At Facebook, we have tens of thousands of components written as classes, and we have absolutely no plans to rewrite them. Instead, we are starting to use Hooks in the new code side by side with classes."

    Hopefully this article has inspired you to hook into your full React potential, or maybe you decided to not bother learning and using yet another API. Either way, let me know your opinion about Hooks, and where you see them going in the future. ✨ Happy Hooking! ✨

    좋은 웹페이지 즐겨찾기