Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
Redux and Context API are two different approaches to state management in React applications. Each of them has its advantages and use cases.
Context API Advantages:
Context API Disadvantages:
Redux Advantages:
Redux Disadvantages:
// Creating context
const ThemeContext = React.createContext();
// Provider
function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
// Usage
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>
);
}
Use Context API when:
Use Redux when:
Recommendation:
Start with Context API for simple cases, and move to Redux when you feel you need its additional capabilities.