너의 면접을 위해 준비하다

현재, 만약 당신이 나처럼 새로운react 개발자라면, 나는 당신이 기술 라운드에서react 갈고리에 관한 문제를 겪은 적이 있다고 확신합니다.이 블로그는 9개의 내장된 React 갈고리를 수정하는 자원으로 사용할 수 있다.
소개가 끝난 후에 시작합시다!

  • useState
    사람들은 보통 상태와 도구를 혼합하지만, 그것들 사이에는 매우 큰 차이가 있다.

    Props are actually what you pass to a component from outside of it. It can only be changed from outside the component.

    State are values which is triggered inside the component itself. It is also mutable by the component.


    useState는 로컬 상태를 추가하기 위해 기능 구성 요소 내부에서 호출된 갈고리입니다.React는 다시 렌더링 사이에 상태 값을 유지합니다.
    useState는 현재 상태 값과 함수를 되돌려줍니다. 이 함수는 업데이트를 허용합니다.
    useState는 매개 변수, 즉 초기 상태만 수락합니다.아래의 예에서 그것은 Name이다.
    응용 프로그램 상태를 변경하면 DOM 자체가 자동으로 다시 나타나 새 값을 표시합니다.
    import {useState} from "react";
    
    const StateTutorial = () => {
        const [inputValue, setInputValue] = useState("Name")
        let onChange = (event) => {
            const newValue = event.target.value;
            setInputValue(newValue);
        }
    
        return(
            <div>
                <input placeholder="Enter your name.." onChange={onChange}/>
                {inputValue}
            </div>
        )
    }
    export default StateTutorial;
    
    일반적으로 기능 어셈블리가 종료되면 변수는 "사라짐"되지만 상태 변수는 React에서 유지됩니다.

  • 사용자 교육자
    useState를 사용할 때 상태 관리 논리는 구성 요소 주체의 중요한 부분을 차지한다. 이것은react 구성 요소가 출력을 생성하는 논리를 포함해야 하기 때문이다.이상적인 상황에서 상태 관리는 반드시 그 단독 공간에서 완성해야 한다. 그렇지 않으면 우리는 렌더링 논리와 상태 관리의 혼합을 얻을 수 있기 때문에 유지보수와 읽기가 매우 어렵다!
    이 문제를 해결하기 위해서,react는useReducer 갈고리를 제공하여 구성 요소에서 상태 관리를 추출합니다.
    useReducer는 두 개의 인자를 받아들인다: Reducer 함수와 초기 상태.
    현재 상태와 분배 함수 두 가지로 구성된 그룹을 되돌려줍니다.

    Initial state: It is the value the state is initialised with.
    Current state: It holds the value of the state currently in.
    Reducer function: The reducer function accepts current state and an action object as parameters. And depending on the action object, the reducer function must update the state and hence returning a new state.
    Action object: The object that describes how to update the state. It has a property called type which describes what kind of state update the reducer function must do.
    Dispatch function: This function dispatches an action object i.e. whenever you want to update the state you simply call the dispatch function with the appropriate action object.


    이 모든 것을 이해하면 우리는 스스로 상태 관리 논리를 작성할 수 있다!
    여기에서 코드를 작성했습니다. 따라서 단추를 누르면 계수기의 값이 증가하고, 번갈아 눌렀을 때 텍스트를 표시하거나 숨깁니다.
    import React, { useReducer } from "react";
    
    const reducer = (state, action) => {
      switch (action.type) {
        case "INCREMENT":
          return { count: state.count + 1, showText: state.showText };
        case "toggleShowText":
          return { count: state.count, showText: !state.showText };
        default:
          return state;
      }
    };
    
    const ReducerTutorial = () => {
      const [state, dispatch] = useReducer(reducer, { count: 0, showText: true });
    
      return (
        <div>
          <h1>{state.count}</h1>
          <button
            onClick={() => {
              dispatch({ type: "INCREMENT" });
              dispatch({ type: "toggleShowText" });
            }}
          >
            Click Here
          </button>
    
          {state.showText && <p>This is a text</p>}
        </div>
      );
    };
    
    export default ReducerTutorial;
    
    TLDR;상태를 업데이트하려면 적당한 조작 대상 호출 dispatch(action) 을 사용하십시오.그리고 동작 대상은 업데이트 상태의 reducer() 함수로 전송됩니다.상태가 Reducer에서 업데이트되면 구성 요소가 다시 렌더링되고 [state, ...] = useReducer(...) hook은 새로운 상태 값을 되돌려줍니다.

  • 사용 효과
    useEffect는 매우 중요한 갈고리로 모든 React 사용자가 그것을 통과해야 한다.
    이 갈고리는 함수를 매개 변수로 하고 렌더링을 화면에 제출한 후에 실행합니다.일반적으로useEffect에 전달된 리셋은 처음에 렌더링된 후에 실행되지만 값을 포함하는 의존항 그룹의 도움말로 변경할 수 있습니다.촉발 효과 변경!
    여기서 종속 배열이 비어 있는 경우에만 프로그램이 처음 렌더링할 때 API를 호출합니다.
    function EffectTutorial() {
      const [data, setData] = useState("");
      const [count, setCount] = useState(0);
    
      useEffect(() => {
        axios
          .get("https://jsonplaceholder.typicode.com/comments")
          .then((response) => {
            setData(response.data[0].email);
            console.log("API WAS CALLED");
          });
      }, []);
    
      return (
        <div>
          Hello World
          <h1>{data}</h1>
          <h1>{count}</h1>
          <button
            onClick={() => {
              setCount(count + 1);
            }}
          >
            Click
          </button>
        </div>
      );
    }
    

    I’m sure I don’t have to explain further how useEffect works as its one of the first few hooks a react developer gets to know about.



  • 레이아웃 효과 사용
    이 갈고리는useEffect와 거의 같다. 그래, 그것들 사이에는 비슷한 점이 있다!둘 다 DOM을 업데이트하고 동일한 유형의 매개변수를 받아들입니다. 그러나 이러한 매개변수 사이에는 근본적인 차이점이 있습니다.
    useLayouteffect는 화면을 렌더링하기 전에 실행하지만, DOM이 업데이트된 후에만 실행됩니다. 이것은 useEffect의 작업 방식과 상반됩니다.
    여기, 조립품은 이 갈고리의 작업 원리를 보여 주었다.
    function LayoutEffectTutorial() {
      const inputRef = useRef(null);
    
      useLayoutEffect(() => {
        console.log(inputRef.current.value);
      }, []);
    
      useEffect(() => {
        inputRef.current.value = "HELLO";
      }, []);
    
      return (
        <div className="App">
          <input ref={inputRef} value="SEKIRO" style={{ width: 400, height: 60 }} />
        </div>
      );
    }
    

    Even though there isn’t a noticeable effect when the useEffect hook is replaced by useLayoutEffect, but it is advised to stick with useEffect unless it causes some problems.



  • useRef
    useRef는 내장된 React 갈고리로 매개 변수를 초기 값으로 받아들이고 인용을 되돌려줍니다.인용은 특수한 속성을 가진current의 대상입니다.

    reference.current access the reference value and reference.current.value updates it.


    참조된 값은 어셈블리 재렌더링 사이에 유지되며 업데이트 상태와 달리 업데이트된 참조는 어셈블리 재렌더링을 트리거하지 않습니다.이것이 바로 내가 결론을 내린 이유이다. 인용 업데이트는 동기화되고 상태 업데이트는 비동기적이다.
    여기서 프로그램은 단추를 누르기만 하면 입력한 모든 내용을 지울 수 있다.
    function RefTutorial() {
      const inputRef = useRef(null);
    
      const onClick = () => {
        inputRef.current.value = "";
      };
      return (
        <div>
          <h1>Pedro</h1>
          <input type="text" placeholder="Ex..." ref={inputRef} />
          <button onClick={onClick}>Change Name</button>
        </div>
      );
    }
    

  • 명령 처리 사용
    React의 데이터 흐름은 단방향이다.즉, 도구를 통해 함수와 데이터를 아래로 전달해야 하며, 구성 요소는 도구로 전달되는 내용에만 접근해야 한다.양방향 데이터 흐름이 필요한 경우, Redux나 React의 상하문 API와 같은 라이브러리를 사용합니다.
    그러나 어떤 경우 레드ux를 가져오거나 상하문을 검으로 손톱을 자르는 것처럼 사용하는 것이 바로 useImperativeHandle의 용무지이다.이것은 우리에게 양방향 흐름을 가진 경량급 해결 방안을 제공할 것이다.
    다음 예는 이 점을 가장 잘 설명한다.
    function ImperializeHandle에서, 우리는 단추 구성 요소를 표시하기 위해useRef hook을 사용했다.현재 나는 우리가 구성 요소에서 인용을 사용할 수 없고, DOM 요소에서useRef를 사용해야 한다는 것을 알고 있지만, forwardRef를 가져왔으니 주의하십시오.

    The forwardRef function allows us to transform a functional component and allow it to accept reference form its parent component. Which is how not only we can grab props but we can also grab any references that is passed through the parent.


    구성 요소UseImperialiveHandle에서ref로 호출할 수 있는 함수를 정의할 수 있습니다. 이것이 바로 본고에서 실현하고자 하는 것입니다.
    그림에서 보듯이 이 갈고리에는 두 개의 매개 변수가 있다.
    a,ref: 부모 구성 요소에서 인용
    b. 한 대상을 되돌려주는 함수
    여전히 많은 사람들을 곤혹스럽게 할 수 있기 때문에, 다음 코드를 코드 편집기에 복사해서 붙여서 실행하는 것이 현명하다.
    import React, { forwardRef, useImperativeHandle, useState } from "react";
    
    const Button = forwardRef((props, ref) => {
      const [toggle, setToggle] = useState(false);
    
      useImperativeHandle(ref, () => ({
        alterToggle() {
          setToggle(!toggle);
        },
      }));
      return (
        <>
          <button>Button From Child</button>
          {toggle && <span>Toggle</span>}
        </>
      );
    });
    
    function ImperativeHandle() {
      const buttonRef = useRef(null);
      return (
        <div>
          <button
            onClick={() => {
              buttonRef.current.alterToggle();
            }}
          >
            Button From Parent
          </button>
          <Button ref={buttonRef} />
        </div>
      );
    }
    
  • 이 모든 정보는 한 번 읽으면 감당하기 어려울 수 있기 때문이다.곧 useContext,useMemo,useCallback 갈고리를 포함하는 또 다른 블로그가 생길 것이다.

    좋은 웹페이지 즐겨찾기