React 후크는 기능 구성 요소에서 상태 및 수명 주기 메서드와 같은 React 기능을 사용할 수 있게 해주는 특수 함수입니다. 이는 구성 요소 모델을 단순화하고 구성 요소 간에 상태 저장 논리를 더 쉽게 공유할 수 있도록 React 16.8에 도입되었습니다.
React Hooks의 주요 기능:
상태 관리: useState와 같은 후크를 사용하면 함수형 구성 요소를 클래스 구성 요소로 변환할 필요 없이 기능 구성 요소의 상태를 추가하고 관리할 수 있습니다.
부작용: useEffect 후크를 사용하면 클래스 구성 요소의 수명 주기 메서드와 유사하게 데이터 가져오기, 구독 또는 DOM 수동 변경과 같은 부작용을 수행할 수 있습니다.
재사용성: 사용자 정의 후크를 사용하면 다양한 구성 요소에서 상태 저장 논리를 캡슐화하고 재사용할 수 있습니다.
클리너 코드: 후크는 구성 요소를 잘 유지하는 데 도움이 됩니다
내장 후크
1 useState
- 설명: 기능 구성 요소에 상태를 추가할 수 있습니다.
- 예:
import React, { useState } from 'react'; const Counter = () => { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onclick="{()"> setCount(count + 1)}>Increment</button> </div> ); };
2 효과 사용
- 설명: 기능 구성 요소에서 데이터 가져오기 또는 구독과 같은 부작용을 관리합니다.
- 예:
import React, { useEffect, useState } from 'react'; const DataFetcher = () => { const [data, setData] = useState(null); useEffect(() => { fetch('https://api.example.com/data') .then(response => response.json()) .then(setData); }, []); return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>; };
3 useContext
- 설명: 소비자 없이도 컨텍스트 값에 대한 액세스를 제공합니다.
- 예:
import React, { useContext } from 'react'; const ThemeContext = React.createContext('light'); const ThemedComponent = () => { const theme = useContext(ThemeContext); return <div classname="{`theme-${theme}`}">Current theme: {theme}</div>; };
4 리듀서 사용
- 설명: Redux와 유사하게 구성 요소의 복잡한 상태 로직을 관리합니다.
- 예:
import React, { useReducer } from 'react'; const initialState = { count: 0 }; const reducer = (state, action) => { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; default: return state; } }; const 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> ); };
5 메모 사용
- 설명: 계산된 값을 메모하여 성능을 최적화하고 불필요한 재계산을 방지합니다.
- 예:
import React, { useMemo, useState } from 'react'; const ExpensiveComputation = ({ number }) => { const compute = (num) => { return num * 1000; // Simulate an expensive computation }; const result = useMemo(() => compute(number), [number]); return <div>Computed Result: {result}</div>; };
6 콜백 사용
- 설명: 종속성 중 하나가 변경된 경우에만 변경되는 콜백 함수의 메모화된 버전을 반환합니다.
- 예:
import React, { useCallback, useState } from 'react'; const Button = React.memo(({ onClick, children }) => { console.log('Button rendered'); return <button onclick="{onClick}">{children}</button>; }); const App = () => { const [count, setCount] = useState(0); const increment = useCallback(() => setCount(c => c + 1), []); return ( <div> <p>Count: {count}</p> <button onclick="{increment}">Increment</button> </div> ); };
7 참조 사용
- 설명: 구성 요소의 전체 수명 동안 지속되는 변경 가능한 참조 객체를 반환하며 DOM 요소에 직접 액세스하는 데 유용합니다.
- 예:
import React, { useRef } from 'react'; const FocusInput = () => { const inputRef = useRef(null); const focusInput = () => { inputRef.current.focus(); }; return ( <div> <input ref="{inputRef}" type="text"> <button onclick="{focusInput}">Focus Input</button> </div> ); };
8 useLayoutEffect
- 설명: useEffect와 유사하지만 모든 DOM 변형 후에 동기적으로 실행되므로 DOM 레이아웃을 측정할 수 있습니다.
- 예:
import React, { useLayoutEffect, useRef } from 'react'; const LayoutEffectExample = () => { const divRef = useRef(); useLayoutEffect(() => { console.log('Height:', divRef.current.clientHeight); }, []); return <div ref="{divRef}">This is a div</div>; };
9 ImperativeHandle 사용
- 설명: 상위 컴포넌트에서 ref를 사용할 때 노출되는 인스턴스 값을 사용자 정의합니다.
- 예:
import React, { useState } from 'react'; const Counter = () => { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onclick="{()"> setCount(count + 1)}>Increment</button> </div> ); };
10 useDebugValue
- 설명: 보다 쉬운 디버깅을 위해 React DevTools의 사용자 정의 후크에 대한 레이블을 표시합니다.
- 예:
import React, { useEffect, useState } from 'react'; const DataFetcher = () => { const [data, setData] = useState(null); useEffect(() => { fetch('https://api.example.com/data') .then(response => response.json()) .then(setData); }, []); return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>; };
맞춤형 후크
11 가져오기 사용
- 설명: API에서 데이터를 가져오기 위한 사용자 정의 후크
- 예:
import React, { useContext } from 'react'; const ThemeContext = React.createContext('light'); const ThemedComponent = () => { const theme = useContext(ThemeContext); return <div classname="{`theme-${theme}`}">Current theme: {theme}</div>; };
12 LocalStorage 사용
- 설명: 상태를 로컬 저장소와 동기화하여 세션 전반에 걸쳐 데이터를 유지합니다.
- 예:
import React, { useReducer } from 'react'; const initialState = { count: 0 }; const reducer = (state, action) => { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; default: return state; } }; const 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> ); };
13 이전 사용
- 설명: 상태나 속성의 이전 값을 반환합니다.
- 예:
import React, { useMemo, useState } from 'react'; const ExpensiveComputation = ({ number }) => { const compute = (num) => { return num * 1000; // Simulate an expensive computation }; const result = useMemo(() => compute(number), [number]); return <div>Computed Result: {result}</div>; };
14 Debounce 사용
- 설명: 값 또는 함수 호출을 디바운스하여 지정된 지연 이후까지 실행을 지연합니다.
- 예:
import React, { useCallback, useState } from 'react'; const Button = React.memo(({ onClick, children }) => { console.log('Button rendered'); return <button onclick="{onClick}">{children}</button>; }); const App = () => { const [count, setCount] = useState(0); const increment = useCallback(() => setCount(c => c + 1), []); return ( <div> <p>Count: {count}</p> <button onclick="{increment}">Increment</button> </div> ); };
15 useOnClickOutside
- 설명: 지정된 요소 외부의 클릭을 감지하여 팝업이나 드롭다운을 닫는 데 유용합니다.
- 예:
import React, { useRef } from 'react'; const FocusInput = () => { const inputRef = useRef(null); const focusInput = () => { inputRef.current.focus(); }; return ( <div> <input ref="{inputRef}" type="text"> <button onclick="{focusInput}">Focus Input</button> </div> ); };
16 useInterval
- 설명: 지정된 간격으로 기능을 반복적으로 실행하는 간격을 설정합니다.
- 예:
import React, { useLayoutEffect, useRef } from 'react'; const LayoutEffectExample = () => { const divRef = useRef(); useLayoutEffect(() => { console.log('Height:', divRef.current.clientHeight); }, []); return <div ref="{divRef}">This is a div</div>; };
17 useTimeout
- 설명: 지정된 지연 후에 기능이 실행되도록 제한 시간을 설정합니다.
- 예:
import React, { useImperativeHandle, forwardRef, useRef } from 'react'; const CustomInput = forwardRef((props, ref) => { const inputRef = useRef(); useImperativeHandle(ref, () => ({ focus: () => { inputRef.current.focus(); } })); return <input ref="{inputRef}" type="text">; }); const Parent = () => { const ref = useRef(); return ( <div> <custominput ref="{ref}"></custominput> <button onclick="{()"> ref.current.focus()}>Focus Input</button> </div> ); };
18 MediaQuery 사용
- 설명: 미디어 쿼리가 일치하는지 확인하여 반응형 디자인 로직을 허용합니다.
- 예:
import { useDebugValue } from 'react'; const useCustomHook = (value) => { useDebugValue(value ? 'Value is true' : 'Value is false'); return value; }; const DebugExample = () => { const isTrue = useCustomHook(true); return <div>Check the React DevTools</div>; };
19 useScrollPosition
- 설명: 현재 창의 스크롤 위치를 추적합니다.
- 예:
import { useState, useEffect } from 'react'; const useFetch = (url) => { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { const fetchData = async () => { const response = await fetch(url); const result = await response.json(); setData(result); setLoading(false); }; fetchData(); }, [url]); return { data, loading }; };
20 KeyPress 사용
- 설명: 특정 키가 눌렸는지 감지합니다.
- 예:
import { useState, useEffect } from 'react'; const useLocalStorage = (key, initialValue) => { const [storedValue, setStoredValue] = useState(() => { try { const item = window.localStorage.getItem(key); return item ? JSON.parse(item) : initialValue; } catch (error) { console.error(error); return initialValue; } }); useEffect(() => { try { window.localStorage.setItem(key, JSON.stringify(storedValue)); } catch (error) { console.error(error); } }, [key, storedValue]); return [storedValue, setStoredValue]; };
요약
이제 이 목록에는 각 후크에 대한 설명이 포함되어 있어 후크의 목적과 사용 사례를 더욱 명확하게 이해할 수 있습니다. 더 자세한 내용이나 예시가 필요하시면 언제든지 문의해주세요!
위 내용은 React 기술 레벨 업: Hooks 이해 및 사용의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

JavaScript 문자열 교체 방법 및 FAQ에 대한 자세한 설명 이 기사는 JavaScript에서 문자열 문자를 대체하는 두 가지 방법 인 내부 JavaScript 코드와 웹 페이지의 내부 HTML을 탐색합니다. JavaScript 코드 내부의 문자열을 교체하십시오 가장 직접적인 방법은 대체 () 메소드를 사용하는 것입니다. str = str.replace ( "find", "replace"); 이 메소드는 첫 번째 일치 만 대체합니다. 모든 경기를 교체하려면 정규 표현식을 사용하고 전역 플래그 g를 추가하십시오. str = str.replace (/fi

이 튜토리얼은 사용자 정의 Google 검색 API를 블로그 또는 웹 사이트에 통합하는 방법을 보여 주며 표준 WordPress 테마 검색 기능보다보다 세련된 검색 경험을 제공합니다. 놀랍게도 쉽습니다! 검색을 Y로 제한 할 수 있습니다

그래서 여기 당신은 Ajax라는이 일에 대해 배울 준비가되어 있습니다. 그러나 정확히 무엇입니까? Ajax라는 용어는 역동적이고 대화식 웹 컨텐츠를 만드는 데 사용되는 느슨한 기술 그룹을 나타냅니다. 원래 Jesse J에 의해 만들어진 Ajax라는 용어

이 기사 시리즈는 2017 년 중반에 최신 정보와 새로운 예제로 다시 작성되었습니다. 이 JSON 예에서는 JSON 형식을 사용하여 파일에 간단한 값을 저장하는 방법을 살펴 봅니다. 키 값 쌍 표기법을 사용하여 모든 종류를 저장할 수 있습니다.

코드 프레젠테이션 향상 : 개발자를위한 10 개의 구문 하이 라이터 웹 사이트 나 블로그에서 코드 스 니펫을 공유하는 것은 개발자에게 일반적인 관행입니다. 올바른 구문 형광펜을 선택하면 가독성과 시각적 매력을 크게 향상시킬 수 있습니다. 티

손쉬운 웹 페이지 레이아웃에 대한 jQuery 활용 : 8 에센셜 플러그인 jQuery는 웹 페이지 레이아웃을 크게 단순화합니다. 이 기사는 프로세스를 간소화하는 8 개의 강력한 JQuery 플러그인을 강조합니다. 특히 수동 웹 사이트 생성에 유용합니다.

이 기사는 JavaScript 및 JQuery Model-View-Controller (MVC) 프레임 워크에 대한 10 개가 넘는 튜토리얼을 선별 한 것으로 새해에 웹 개발 기술을 향상시키는 데 적합합니다. 이 튜토리얼은 Foundatio의 다양한 주제를 다룹니다

핵심 포인트 JavaScript에서는 일반적으로 메소드를 "소유"하는 객체를 말하지만 함수가 호출되는 방식에 따라 다릅니다. 현재 객체가 없으면 글로벌 객체를 나타냅니다. 웹 브라우저에서는 창으로 표시됩니다. 함수를 호출 할 때 이것은 전역 객체를 유지하지만 객체 생성자 또는 그 메소드를 호출 할 때는 객체의 인스턴스를 나타냅니다. call (), apply () 및 bind ()와 같은 메소드를 사용 하여이 컨텍스트를 변경할 수 있습니다. 이 방법은 주어진이 값과 매개 변수를 사용하여 함수를 호출합니다. JavaScript는 훌륭한 프로그래밍 언어입니다. 몇 년 전,이 문장은있었습니다


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기
