Redux라는 것을 쓰면 모두 전역 상태로 만들게 됨. 이것은 좋은 방법은 아님. 큰 프로젝트 같은 경우 리덕스 코드가 있으면 상태가 너무 많아 지옥을 경험하게 됨.. 홀홀 전역 상태라는 것은 없으면 더 좋다.
그러면 전역 상태는 무엇이 되어야 하나? 사용자.
참고
//Provider
const store = createStore(rootReducer)
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
//Consumer
import React from 'react'
import { useSelector } from 'react-redux'
export const CounterComponent = () => {
const counter = useSelector((state) => state.counter)
return <div>{counter}</div>
} // useSelector가 생겼다
function FirstComponent({ children }) {
return (
<div>
<h3>I am the first component</h3>;
{ children }
</div>
);
}
function SecondComponent({ children }) {
return (
<div>
<h3>I am the second component</h3>;
{children}
</div>
);
}
function ThirdComponent({ children }) {
return (
<div>
<h3>I am the third component</h3>
{children}
</div>
);
}
function ComponentNeedingProps({ content }) {
return <h3>{content}</h3>
}
export default function App() {
const content = "Who needs me?";
return (
<div className="App">
<FirstComponent>
<SecondComponent>
<ThirdComponent>
<ComponentNeedingProps content={content} />
</ThirdComponent>
</SecondComponent>
</FirstComponent>
</div>
);
}
children을 줘서 props drilling 을 해결함
LRU (Least Recently Used)
운영체제의 페이지 교체 알고리즘 중 하나이다. 페이지를 교체할 때 가장 오랫동안 사용되지 않은 페이지를 교체 대상으로 삼는 기법이다.
//fetch util
const updateLabel = (id, inputValue) => {
return fetch(`http://localhost:3001/label/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ description: inputValue }),
}).then((res) => res.json());
};
//Component
export const LabelList = ({ id, name, description }) => {
const queryClient = useQueryClient();
const [isEditingMode, setEditingMode] = useState(false);
const [inputValue, setInputValue] = useState('');
const PatchMutation = useMutation((idx) => updateLabel(idx, inputValue), {
onSuccess: (data, variables, context) => {
// 캐시 업데이트 (캐시 무효화)
queryClient.invalidateQueries('labels');
setEditingMode(false);
},
});
//event handler
const updateList = ({target}) => {
const idx = target.closest('li').dataset.idx;
PatchMutation.mutate(idx);
};
.....
......
//Atom.js
import { atom } from "recoil";
export const numState = atom({
key: "count",
default: 1
});
export const clickCountAtom = atom({
key: "clickCount",
default: 0
});
export const authenticationAtom = atom({
key: "authentication",
default: false
});
// View.js
import { useRecoilState } from "recoil";
import { clickCountAtom, authenticationAtom } from "./atoms/atoms";
const ClickCountView = () => {
console.log("clickCountvIEW CALLED");
const [clickCount] = useRecoilState(clickCountAtom);
return (
<>
<div>클릭 횟수 : {clickCount}</div>
<PrivateView />
</>
);
};
https://react.dev/reference/react/useSyncExternalStore
상태 관리 라이브러리의 기능을 표준화해서 만들어두는 작업을 리액트가 계속 진행중임
https://legacy.reactjs.org/docs/error-boundaries.html
https://codepen.io/gaearon/pen/wqvxGa?editors=0010