Redux aer en foerutsaegbar tillstaandshanterare foer JavaScript-appar baserad pa enkelriktat datafloede.
Grundbegrepp och Skapa Store
import { createStore } from 'redux';
// Reducer-funktion: ren funktion som beraeknar naesta tillstaand
function counterReducer(state = { value: 0 }, action) {
switch (action.type) {
case 'counter/incremented':
return { value: state.value + 1 };
case 'counter/decremented':
return { value: state.value - 1 };
default:
return state;
}
}
// Skapa store
const store = createStore(counterReducer);
// Prenumerera pa tillstaandsaendringar
const unsubscribe = store.subscribe(() => {
console.log('Aktuellt tillstaand:', store.getState());
});
// Skicka actions
store.dispatch({ type: 'counter/incremented' }); // { value: 1 }
store.dispatch({ type: 'counter/decremented' }); // { value: 0 }
Action Creators och Middleware
// Action Creator
const incrementBy = (amount) => ({
type: 'counter/incrementBy',
payload: amount
});
// Middleware-moenster (loggning, asynkrona thunks)
const loggerMiddleware = (storeAPI) => (next) => (action) => {
console.log('Skickar action:', action);
const result = next(action);
console.log('Naesta tillstaand:', storeAPI.getState());
return result;
};
React Redux Hooks (useSelector och useDispatch)
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
export function Counter() {
const count = useSelector((state) => state.value);
const dispatch = useDispatch();
return (
<div>
<span>Count: {count}</span>
<button onClick={() => dispatch({ type: 'counter/incremented' })}>
+
</button>
</div>
);
}
Moderna Redux Toolkit (RTK)
Moderna Redux-applikationer anvaender Redux Toolkit foer att minimera boilerplate-kod:
import { createSlice, configureStore } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: (state) => { state.value += 1; },
decrement: (state) => { state.value -= 1; }
}
});
export const { increment, decrement } = counterSlice.actions;
export const store = configureStore({ reducer: counterSlice.reducer });