Загрузка...
Загрузка...
Продолжая работу с платформой, вы принимаете условия Политики конфиденциальности и использование файлов cookie.
Redux и Context API — это два разных подхода к управлению состоянием в React-приложениях. Каждый из них имеет свои преимущества и случаи использования.
Преимущества Context API:
Недостатки Context API:
Преимущества Redux:
Недостатки Redux:
// Создание контекста
const ThemeContext = React.createContext();
// Provider
function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
// Использование
function ThemedButton() {
const { theme, setTheme } = useContext(ThemeContext);
return (
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Current theme: {theme}
</button>
);
}
// Action Types
const SET_THEME = 'SET_THEME';
// Action Creator
const setTheme = (theme) => ({
type: SET_THEME,
payload: theme
});
// Reducer
const themeReducer = (state = { theme: 'light' }, action) => {
switch (action.type) {
case SET_THEME:
return { ...state, theme: action.payload };
default:
return state;
}
};
// Component
function ThemedButton() {
const theme = useSelector(state => state.theme);
const dispatch = useDispatch();
return (
<button onClick={() => dispatch(setTheme(theme === 'light' ? 'dark' : 'light'))}>
Current theme: {theme}
</button>
);
}
Используйте Context API, когда:
Используйте Redux, когда:
Рекомендация:
Начните с Context API для простых случаев, и переходите к Redux, когда почувствуете, что вам нужны его дополнительные возможности.