🔬 Praktikum 12: State Management (Context API & Redux)
Tujuan Praktikum
A. Context API (Solusi Sederhana)
Buat Context untuk Theme
// context/ThemeContext.js
import { createContext, useContext, useState } from 'react';
const ThemeContext = createContext();
export function ThemeProvider({ children }) {
const [isDark, setIsDark] = useState(false);
const toggle = () => setIsDark(!isDark);
const theme = {
isDark,
toggle,
colors: isDark
? { bg: '#1a1a1a', text: '#fff', card: '#2d2d2d' }
: { bg: '#f5f5f5', text: '#000', card: '#fff' },
};
return (
{children}
);
}
export const useTheme = () => useContext(ThemeContext);
Gunakan di Component
// App.js
import { ThemeProvider, useTheme } from './context/ThemeContext';
import { View, Text, Switch, StyleSheet } from 'react-native';
function HomeScreen() {
const { isDark, toggle, colors } = useTheme();
return (
Mode: {isDark ? 'Gelap' : 'Terang'}
);
}
export default function App() {
return (
);
}
B. Redux Toolkit (Aplikasi Kompleks)
Install Redux
npm install @reduxjs/toolkit react-redux
Buat Slice (store/todoSlice.js)
import { createSlice } from '@reduxjs/toolkit';
const todoSlice = createSlice({
name: 'todos',
initialState: { items: [] },
reducers: {
addTodo: (state, action) => {
state.items.push({
id: Date.now().toString(),
text: action.payload,
done: false,
});
},
toggleTodo: (state, action) => {
const item = state.items.find(t => t.id === action.payload);
if (item) item.done = !item.done;
},
deleteTodo: (state, action) => {
state.items = state.items.filter(t => t.id !== action.payload);
},
},
});
export const { addTodo, toggleTodo, deleteTodo } = todoSlice.actions;
export default todoSlice.reducer;
Setup Store (store/index.js)
import { configureStore } from '@reduxjs/toolkit';
import todoReducer from './todoSlice';
export const store = configureStore({
reducer: { todos: todoReducer },
});
Gunakan di App
import { Provider, useSelector, useDispatch } from 'react-redux';
import { store } from './store';
import { addTodo, toggleTodo, deleteTodo } from './store/todoSlice';
function TodoApp() {
const todos = useSelector(state => state.todos.items);
const dispatch = useDispatch();
const [text, setText] = useState('');
return (
);
}
export default function App() {
return ;
}
C. Context vs Redux
D. Tugas Praktikum 12
1. Implementasikan Theme toggle (dark/light) dengan Context API
2. Buat Todo App dengan Redux Toolkit (add, toggle, delete)
3. Gabungkan keduanya dalam satu aplikasi
4. Screenshot dan kumpulkan source code