props-drilling: 부모 컴포넌트에서 특정 자식 컨포넌트로 데이터가 이동하는 과정으로, 데이터를 전달만 하는 컴포넌트가 존재하게 된다.
props-drilling 을 막는 방법
1) React Context API.
import React, { createContext, useContext, useState } from 'react';
const CounterContext = createContext();
function CounterProvider({ children }) {
const [count, setCount] = useState(0);
return (
<CounterContext.Provider value={{ count, setCount }}>
{children}
</CounterContext.Provider>
);
}
function useCounter() {
return useContext(CounterContext);
}
2) Redux
import { createStore } from 'redux';
const initialState = {
count: 0,
};
function counterReducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return { ...state, count: state.count + 1 };
default:
return state;
}
}
const store = createStore(counterReducer);
3) Mobx
import { observable, action } from 'mobx';
class CounterStore {
@observable count = 0;
@action
increment() {
this.count++;
}
}
const counterStore = new CounterStore();
4) Recoil
import { atom, selector, useRecoilState, useRecoilValue } from 'recoil';
const countState = atom({
key: 'countState',
default: 0,
});
const incrementState = selector({
key: 'incrementState',
set: ({ set }) => {
set(countState, (count) => count + 1);
},
});
function Counter() {
const [count, setCount] = useRecoilState(countState);
const increment = useRecoilValue(incrementState);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(increment)}>Increment</button>
</div>
);
}
5) React-Query
// Without React Query
fetch('/api/data').then(response => response.json()).then(data => ...);
// With React Query
const { data } = useQuery('data', () => fetch('/api/data')
.then(response => response.json())
);
const { data, fetchNextPage } = useInfiniteQuery(['items'], fetchPageData);
출처:
https://medium.com/analytics-vidhya/props-drilling-in-react-js-934120a4906b
https://medium.com/@AlexanderObregon/comparing-redux-with-alternative-state-management-solutions-mobx-context-api-and-recoil-7694091dd87c
https://medium.com/@kvs.sankar23/react-query-is-the-best-thing-that-happened-to-react-abd92553e953