Apa itu useReducer ?
useReducer adalah hook yang digunakan untuk mengelola state lokal dalam komponen React menggunakan pola reducer. Ini sangat berguna ketika logika pembaruan state kompleks atau ketika state bergantung pada nilai sebelumnya.
useReducer merupakan alternatif dari useState. Biasanya digunakan ketika Anda memiliki logika state yang kompleks yang melibatkan beberapa sub-nilai, atau ketika state berikutnya bergantung pada state sebelumnya.
beriut contoh code penggunaan useReducer :
import React, { useReducer } from "react";
//Reducer Function
const reducer = (state, action) => {
switch (action.type) {
case "INCREMENT":
return state + 1;
case "DECREMENT":
return state - 1;
default:
return state;
}
};
export default function App() {
// Initial state and reducer function
const [count, dispatch] = useReducer(reducer, 0);
return (
<div>
<h2>Counter with useReducer</h2>
<h4>Count: {count}</h4>
<button onClick={() => dispatch({ type: "INCREMENT" })}>Increment</button>
<button onClick={() => dispatch({ type: "DECREMENT" })}>Decrement</button>
</div>
);
}
Karena type adalah string biasa, typo sekecil apapun bisa bikin reducer tidak mengenali action dan tidak mengubah state. Untuk mengakali hal ini kita bisa membuat konstanta terpisah untuk mengelola action.type
Struktur Folder
src/
├── App.js
└── actionTypes.js
File src/actionTypes.js
export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';
Gunakan di file App.jsx
import React, { useReducer } from "react";
import { INCREMENT, DECREMENT } from "./actionTypes"; // ✅ Import konstanta
// Reducer Function
const reducer = (state, action) => {
switch (action.type) {
case INCREMENT:
return state + 1;
case DECREMENT:
return state - 1;
default:
return state;
}
};
export default function App() {
const [count, dispatch] = useReducer(reducer, 0);
return (
<div>
<h2>Counter with useReducer</h2>
<h4>Count: {count}</h4>
<button onClick={() => dispatch({ type: INCREMENT })}>Increment</button>
<button onClick={() => dispatch({ type: DECREMENT })}>Decrement</button>
</div>
);
}
Sekarang kamu tidak perlu takut typo "INCREMET" atau "DECREMET" karena IDE akan bantu auto-complete.
0 Komentar