-
React Hooks (1)웹개발/JavaScript 2021. 1. 6. 22:41
· 리액트의 신박한 기능으로 state, component에 대한 것들을 바꿔놓을 예정
· functional component에서 state를 가질 수 있게 해줌
· 앱을 리액트 훅으로 만든다면, class component, did mount, render ... 이런 것들을 하지 않아도 됨
· 모든 것은 하나의 function이 되는 것 (functional programmimg 스타일이 된다는 뜻)
· 훅의 역사는 recompose 라이브러리에서 시작됨 (함수형 프로그래밍이고, state를 줌)
· 즉, recompose + 리액트팀의 결합 = 리액트 훅
- React Hooks를 사용하지 않는 경우
import React, {Component} from "react";
class App extends Component {
state={
count:0
};
modify = (n) => {
this.setState({
count:n
});
};
render() {
const { count } = this.state;
return(
<>
<div>{ count }</div>
<button onClick={() => this.modify(count+1)}>Increment</button>
</>
);
}
}
export default App;
- React Hooks를 사용하는 경우
import React, {Component, useState} from "react";
const App = () => {
const [count, setCount] = useState(0);
return (
<>
{ count }
<button onClick={() => setCount(count+1)}>Increment</button>
</>
)
}
export default App;
· useState는 2개를 줌. 하나는 value, 두번째는 이를 변경하는 방법
· 우리는 이 [count, setCount] array로 작업을 하는데, 왜냐면 useState가 주는 것이 array이기 때문
· useState는 array를 리턴 !
· 즉, usrState가 리액트 state 매니지먼트의 밑으로 들어가 훅~을 땡기는 것
class component에서는 일일히 우리가 작성해줘야 함
import logo from './logo.svg';
import './App.css';
import React, {Component, useState} from "react";
const App = () => {
const [count, setCount] = useState(0);
const [email, setEmail] = useState("");
const UpdateEmail = e => {
const {
target: {value}
} = e;
setEmail(value);
};
return (
<>
{ count }
<button onClick={() => setCount(count+1)}>Increment</button>
<button onClick={() => setCount(count-1)}>Decrement</button>
<input placeholder="Email" value={email} onChange={UpdateEmail}></input>
</>
)
}
export default App;
· 훅에는 Effect Hook이라는 것도 있음
: component did mount, did update와 비슷함, 이들은 주로 API에서 데이터를 요청할 때 사용
* useState
· 항상 2개의 value를 return
예제)
import React, {useState} from "react";
import ReactDOM from "react-dom";
function App(){
const [item, setItem] = useState(1);
return (
<div className="App">
<h1>{item}</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
· item만 사용하고 싶다면 const [item] = useState(1) 대신에 const item = useState(1)[0]을 사용
또는 function을 수정하고 싶다면 const item=useState(1)[1]
· useState를 부른 곳에 값을 return을 해줄 수 있음
import React, {useState} from "react";
import ReactDOM from "react-dom";
function App(){
const [item, setItem] = useState(1);
const incrementItem = () => setItem(item+1);
const decrementItem = () => setItem(item-1);
return (
<div className="App">
<h1>{item}</h1>
<h2>Start editing to see some magic happen!</h2>
<button onClick={incrementItem}>Increment</button>
<button onClick={decrementItem}>Decrement</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
- 위 코드를 Class Component로 변경
class AppUgly extends React.Component{
state = {
item: 1
}
render(){
const {item} = this.state;
return (
<div className="App">
<h1>Hello {item}</h1>
<h2>Start editing to see some magic happen!</h2>
<button onClick={this.incrementItem}>Increment</button>
<button onClick={this.decrementItem}>Decrement</button>
</div>
);
}
incrementItem=()=>{
this.setState(state => {
return {
item: state.item + 1
};
});
};
decrementItem=()=>{
this.setState(state => {
return {
item: state.item - 1
};
});
};
}
const rootElement = document.getElementById("root");
ReactDOM.render(<AppUgly />, rootElement);
· hooks가 생기기 전에 우리는 state를 함수형 component에 사용할 수 없었음
· state를 가지고 작업을 하고 싶으면 Class Component 형태로 만들어야 했음
· Class Component는 this와 같은 문장 규칙과 Render와 같은 사용하는 방법을 고려해야 하지만 hook를 사용한다면 이러한 것들을 신경쓰지 않아도 됨
· return에다가 뿌려주고 그 위에 적어주기만 하면 됨
- useInput
: 기본적으로 input을 업데이트 함
import React, {useState} from "react";
import ReactDOM from "react-dom";
const useInput = (initialValue) => {
const [value, setValue] = useState(initialValue);
const onChange = event => {
console.log(event.target);
};
return { value, onChange };
}
const App = () => {
const name = useInput("Mr.");
return (
<div className="App">
<h1>Hello</h1>
<input placeholder="Name" {...name} />
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
· react에게 있어 혁명적
: 다른 function에서 이벤트를 처리할 수 있기 때문
이건 react component가 아니라 완전히 다른 function
그리고 우리의 이벤트를 분리된 파일, 다른 entity에 연결해서 처리할 수 있음
- useInput part Two
(hooks x)
import React, {useState} from "react";
import ReactDOM from "react-dom";
const useInput = (initialValue, validator) => {
const [value, setValue] = useState(initialValue);
const onChange = event => {
const {
target: {value}
} = event;
let willUpdate = true;
if(typeof validator === "function"){
willUpdate = validator(value);
}
if(willUpdate){
setValue(value);
}
};
return { value, onChange };
}
const App = () => {
const maxLen = (value) => value.length <= 10;
//const maxLen = value => !value.includes("@");
const name = useInput("Mr.", maxLen);
return (
<div className="App">
<h1>Hello</h1>
<input placeholder="Name" {...name} />
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
- useTabs
import React, {useState} from "react";
import ReactDOM from "react-dom";
const content = [
{
tab: "Section 1",
content: "I'm the content of the Section 1"
},
{
tab: "Section 2",
content: "I'm the content of the Section 2"
}
]
const useTabs = (initialTab, allTabs) => {
if(!allTabs || !Array.isArray(allTabs)){
return ;
}
const [ currentIndex, setCurrentIndex ] = useState(initialTab);
return {
currentItem: allTabs[currentIndex],
changeItem: setCurrentIndex
};
};
const App = () => {
const {currentItem, changeItem} = useTabs(0, content);
return (
<div className="App">
{content.map((section, index) => (
<button onClick={()=>changeItem(index)}>{section.tab}</button>
))}
<div>{currentItem.content}</div>
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
· useState 사용법
· set state는 모든 걸 새로고침 해줌 (re-render 해주는 것)
render function이 없다고 render가 안되는 것이 아님
'웹개발 > JavaScript' 카테고리의 다른 글
React Hooks (3) (0) 2021.01.12 React Hooks (2) (0) 2021.01.10 ReactJS: props, state (0) 2021.01.06 ReactJS로 영화 웹 서비스 만들기 (0) 2021.01.04 ReactJS (5) (0) 2021.01.04