1. react의 상태 관리
2. props를 이용한 상태 관리의 문제점
3. recoil
4. Atoms
HomeComponent.tsx
import { CommonComponent, CommonSubComponent, Container, SubTitle, Title } from "src/components/commons/Commons"
import Temperature from "src/components/home/atoms/Temperature";
import useWeatherData from "src/hooks/useWeatherData";
export default function HomeComponent () : React.ReactElement {
const {data, temp, weather} = useWeatherData();
return (
<Container>
<Temperature temp={temp}></Temperature>
</Container>
)
}
Temperature.tsx
import styled from "styled-components"
export const WeatherContent = styled.div`
display: flex;
justify-content: center;
font-size: 45px;
`
interface TemperatureProps {
temp : number;
}
export default function Temperature ({ temp } : TemperatureProps) : React.ReactElement {
return(
<WeatherContent>{temp + "℃"}</WeatherContent>
)
}
props drilling - props를 오로지 하위 컴포넌트로 전달하는 용도로만 쓰이는 컴포넌트들을 거치면서 React Component 트리의 한 부분에서 다른 부분으로 데이터를 전달하는 과정
A state management library for React
더 이상
props drilling
이 발생하지 않으며, atoms에 등록된 상태는 모든 컴포넌트들이 구독할 수 있는 전역 상태가 되는 것
install
npm i recoil
index.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { RecoilRoot } from 'recoil';
import App from './App';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<React.StrictMode>
<RecoilRoot>
<App />
</RecoilRoot>
</React.StrictMode>
);
An atom represents state in Recoil. The atom() function returns a writeable RecoilState object.
storage.ts
export const questionNum = atom({
key: "questionNum",
default : 0,
})
key, default
를 설정할 수 있음import { useRecoilState } from "recoil";
import { answerState, questionState } from "src/utils/storage";
export default function useCreate() {
const [question, setQuestion] = useRecoilState(questionState);
const [answer, setAnswer] = useRecoilState(answerState);
const handleCreateQuestion = (question : string, answer : string) => {
setQuestion('');
setAnswer('');
}
}
useLoadAllQuestion.ts
import { useRecoilValue } from "recoil";
import { questionNum } from "src/utils/storage";
export default function useLoadAllQuestion() {
const questionNumber = useRecoilValue(questionNum);
return {
questionNumber,
}
}
useDelete.ts
import { useSetRecoilState } from "recoil";
import { questionNum, questionSet } from "src/utils/storage";
export default function useDelete() {
const setQuiz = useSetRecoilState(questionSet);
const setAllQuestion = useSetRecoilState<number>(questionNum);
const handleDeleteQuestion = (id:number) => {
setQuiz((oldQuiz) => {
const index = oldQuiz.findIndex(question => question.id === id);
return [...oldQuiz.slice(0, index), ...oldQuiz.slice(index+1)];
})
setAllQuestion((prev:number) => prev-1);
}
return {
handleDeleteQuestion
}
}
pon06188님 - Recoil
https://velog.io/@pon06188/Recoil
juno7803님 - Recoil 200% 활용하기
wooder2050님 - 리코일(Recoil)은 왜 만든 건데?