Posted by masis on Sat Jan 14 2023
Redux and the Context API are both libraries in JavaScript that are used for managing application state.
Redux is a library that implements the principles of the Flux architecture, which is commonly used with React applications. It allows you to manage the state of your application in a centralized store, and you can use actions and reducers to update the state. Here is an example of a simple Redux store and reducer
// store.js
import { createStore } from 'redux';
const initialState = {
count: 0
};
function reducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
}
export const store = createStore(reducer);
// component.js
import { useState } from 'react';
import { store } from './store';
export default function MyComponent() {
const [state, setState] = useState(store.getState());
store.subscribe(() => {
setState(store.getState());
});
return (
<div>
<button onClick={() => store.dispatch({ type: 'INCREMENT' })}>+</button>
<button onClick={() => store.dispatch({ type: 'DECREMENT' })}>-</button>
<p>{state.count}</p>
</div>
);
}
// theme-context.js
import { createContext } from 'react';
export const ThemeContext = createContext('light');
// theme-provider.js
import { useState } from 'react';
import { ThemeContext } from './theme-context';
export default function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={[theme, setTheme]}>
{children}
</ThemeContext.Provider>
);
}
// component.js
import { useContext } from 'react';
import { ThemeContext } from './theme-context';
export default function MyComponent() {
const [theme, setTheme] = useContext(ThemeContext);
return (
<div>
<button onClick={() => setTheme('dark')}>Dark Theme</button>
<button onClick={() => setTheme('light')}>Light Theme</button>
<p>Current theme: {theme}</p>
</div>
);
}