본문 바로가기

Frontend/React

useEffect

useEffect( fn, [ deps ])

1. deps가 빈배열일 때 처음에만 렌더링함. (리렌더링 하지 않음)

2. deps위치의 특정값이 변화할때만 렌더링함.

+cleanup 함수 반환

import { useState, useEffect } from "react";

function App() {
  const [counter, setValue] = useState(0);
  const [keyword, setKeyworld] = useState("")
  const onClick = () => setValue((prev) => prev + 1);
  const onChange = (event) => setKeyworld(event.target.value);
  console.log("I run all the time");
  useEffect(() => {
    console.log("I run only once");
  }, []);
  useEffect(()=>{
    console.log("I run when 'keyword' changes");
  }, [keyword]);
  useEffect(()=>{
    console.log("I run when 'counter' changes");
   }, [counter]);
   useEffect(()=>{
    console.log("I run when keyword and counter changes");
   }, [keyword, counter]);
  return (
   <div>
     <input 
     value = {keyword}
     onChange = {onChange} 
     type ="text"
     placeholder ="Search here..." />
    <h1>{counter}</h1>
    <button onClick={onClick}>click me</button>
   </div>
  );
}

export default App;

 

참고 자료 : https://xiubindev.tistory.com/100

 

React Hooks : useEffect() 함수

useEffect 함수는 리액트 컴포넌트가 렌더링 될 때마다 특정 작업을 실행할 수 있도록 하는 Hook 이다. useEffect는 component가 mount 됐을 때, component가 unmount 됐을 때, component가 update 됐을 때, 특정..

xiubindev.tistory.com

 

'Frontend > React' 카테고리의 다른 글

map  (0) 2022.01.24
To Do List (Enrollent)  (0) 2022.01.22
Props & memo  (0) 2022.01.11
Unit Converter  (0) 2022.01.10
JSX란?  (0) 2022.01.04