useState, useEffect, useCallback, useMemo

Jayden ·2023년 4월 20일
0

1. useState

1) 클래스 컴포넌트로 count 값 설정

import React from 'react';

export default class Example1 extend React.Component {
	state = {count : 0};
  
  render(){
   const {count} = this.state;
   
    return (
      <div>
      	<p>You clicked {count} times</p>
  		<button onClick={this.click}>Click me</button>
      </div>
    );
  }

click = () => {
  this.setState({count : this.state.count + 1})
};
}

2) useState 사용

함수 컴포넌트에서 사용되는 hook이며,

클래스 컴포넌트에서의 this.state를 대체한다.

useState 사용할 경우 배열을 리턴한다.

첫번째 값은 현재 상태, 두번째 값은 현재 상태를 변경하는 setter 함수를 리턴한다.

import React from 'react';


export default function Example2() {
  
const [const, setCount] = React.useState(0);
  
return (
     //클래스 컴포넌트가 아니므로 this를 사용하지 않는다. 
 	 <div>
      	<p>You clicked {count} times</p>
		<button onClick={click}>Click me</button>
      </div>
   
);

function click(){
 		setCount(count+1); 
	}
}
  

state값을 객체로 설정할 수 도 있다.

import React from 'react';


//useState => count
//useState => {count : 0};

export default function Example3() {
  
const [state, setState] = React.useState({count : 0});
  
return (
 	 <div>
      	<p>You clicked {state.count} times</p>
		<button onClick={click}>Click me</button>
      </div>
   
);

function click(){
 	setCount({count : state.count +1}); 
	}
}

다음과 같이 setCount 함수를 사용할 경우, 상단의 작성한 const [state, setState] = React.useState({count : 0}); 에 의존적이지 않고 기존 값을 기억하여 값을 변경할 수 있다.

function click(){
 	setCount((state) => (({count : state.count +1}));
	}
}

2. useEffect

다음 라이프사이클 hook을 대체할 수 있다.

  • componentDidMount
  • componentDidUpdate
  • componentWillUnmount
import React from 'react';

export default class Example4 extend React.Component {
  
  state = {count : 0};
  
  render()
  {
    const {count} = this.state;
   
    return (
      <div>
      	<p>You clicked {count} times</p>
  		<button onClick={this.click}>Click me</button>
      </div>
    );
  }

componentDidMount() {
  console.log("componentDidMount", this.state.count)
}

componentDidUpdate() {
  console.log("componentDidUpdate", this.state.count)
}

click = () => {
  		this.setState({count : this.state.count + 1})
	};
}

함수 컴포넌트도 클래스 컴포넌트 처럼 마운트 후, 업데이트 후 부수적으로 실행할 함수를 구현할 수 있다.

import React from 'react';


export default function Example2() {
  
const [const, setCount] = React.useState(0);

  
  
/*useEffect 함수에 두번째 인자가 빈배열이다.
  즉, 최초로 마운트 되었을때만 함수가 실행된다.)
*/
  
React.useEffect(()=>{
  console.log("componentDidMount", count);
},[]);

  
  
/*useEffect 함수에 두번째 인자인 의존성 배열에 count가 존재한다.
  즉, 최초로 마운트 되었을때와 count값이 변경되었을 경우 아래 함수가 실행된다.
*/  
  
React.useEffect(()=>{
  console.log("componentDidMount & componentDidUpdate by count", count);
},[count]);  
  
  
  
return (
 	 <div>
      	<p>You clicked {count} times</p>
		<button onClick={click}>Click me</button>
      </div>
   
);

function click(){
 		setCount(count+1); 
	}
}

useEffect는 클린업 함수를 설정할 수 있다.
다시말해 상태값이 변경이 되고 컴포넌트를 업데이트(재렌더링)하기 이전에 처리할 함수를 설정할 수 있다.

import React from 'react';


export default function Example2() {
  
const [const, setCount] = React.useState(0);
  
React.useEffect(()=>{
  console.log("componentDidMount", count);

  return ()=> {
   //cleanup
   //componentWillUnmount    
  };

},[]);
React.useEffect(()=>{
  console.log("componentDidMount & componentDidUpdate by count", count);
  
return ()=>{
  	//cleanup
  	console.log("cleanup by count", count);
	};
},[count]);  
  
  
  
return (
 	 <div>
      	<p>You clicked {count} times</p>
		<button onClick={click}>Click me</button>
      </div>
   
);

function click(){
 		setCount(count+1); 
	}
}
profile
J-SONE 프론트엔드 개발자

0개의 댓글