Gimana cara kerja useReducer?

Photo by Lautaro Andreani on Unsplash
  • store — objek yang tidak dapat diubah (immutable) yang menyimpan data state aplikasi
  • reducer — fungsi yang mengembalikan beberapa data state, dipicu oleh aksi type
  • action — objek yang memberi tahu reducer cara mengubah state. Harus berisi properti type, dan dapat berisi properti payload secara opsional
import { createStore } from 'redux'

const store = createStore(reducer, [preloadedState], [enhancer])
const initialState = { count: 0 }

const [state, dispatch] = useReducer(reducer, initialState)
(state = initialState, action) => newState
// perhatikan bahwa statenya = initialState dan memberikan state baru

const reducer = (state = initialState, action) => {
switch (action.type) {
case 'ITEMS_REQUEST':
return Object.assign({}, state, {
isLoading: action.payload.isLoading
})
case ‘ITEMS_REQUEST_SUCCESS':
return Object.assign({}, state, {
items: state.items.concat(action.items),
isLoading: action.isLoading
})
default:
return state;
}
}
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
{ type: ITEMS_REQUEST_SUCCESS, payload: { isLoading: false } }

// pembuat aksi
export function itemsRequestSuccess(bool) {
return {
type: ITEMS_REQUEST_SUCCESS,
payload: {
isLoading: bool,
}
}
}

// dispatch aksi dengan redux
dispatch(itemsRequestSuccess(false)) // untuk meminta fungsi dispatch, kita perlu memberikan action sebagai argumen ke fungsi dispatch
// bukan kode lengkap
switch (action.type) {
case 'increment':
return {count: state.count + 1};
default:
throw new Error();
}

// dispatch action dengan useReducer
<button onClick={() => dispatch({type: 'increment'})}>Increment</button>

--

--

A learner just like you

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store