JavaScript 함수
로 구현되며, 주로 간단한 상태나 라이프사이클 메서드
를 사용하지 않는 컴포넌트에 사용된다.EX.
import React from 'react'; const FunctionalComponent = () => { return ( <div> <p>This is a functional component.</p> </div> ); }; export default FunctionalComponent;
React Hooks
를 활용하여 함수형 컴포넌트에서도 상태(state)나 생명주기 메서드와 같은 기능을 사용할 수 있게 되었다.
1. useState:
import React, { useState } from 'react';
const ExampleComponent = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment Count
</button>
</div>
);
};
2. useEffect:
import React, { useState, useEffect } from 'react';
const DataFetchingComponent = () => {
const [data, setData] = useState(null);
useEffect(() => {
// 데이터 가져오기
fetchData()
.then((result) => setData(result))
.catch((error) => console.error(error));
}, []); // 빈 배열은 컴포넌트가 처음 마운트될 때만 실행
return (
<div>
{data ? (
<p>Data: {data}</p>
) : (
<p>Loading data...</p>
)}
</div>
);
};
3. useContext:
Context
에서 값을 가져올 수 있게 해주는 훅이다.import React, { useContext } from 'react';
import MyContext from './MyContext';
const ContextComponent = () => {
const contextValue = useContext(MyContext);
return (
<p>Context Value: {contextValue}</p>
);
};
4. useReducer:
useReducer
는 상태 업데이트 로직을 재사용할 수 있게 해주는 훅입니다. 일반적으로 복잡한 상태 로직을 관리할 때 사용된다.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 ReducerComponent = () => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>
Increment Count
</button>
<button onClick={() => dispatch({ type: 'decrement' })}>
Decrement Count
</button>
</div>
);
};
ES6의 클래스
로 정의되며, React.Component 클래스를 상속받는다.EX.
import React, { Component } from 'react'; class ClassComponent extends Component { render() { return ( <div> <p>This is a class component.</p> </div> ); } } export default ClassComponent;
최근에는 함수형 컴포넌트와 훅스의 도입으로 함수형 컴포넌트가 더 선호되는 경향이 있다.