Menu

1 / 2

useReducer in React — Why It Exists and How to Use It Simply

DEV Community·DHANRAJ S·6 months ago
#Qnl9uW96
#react#javascript#beginners#webdev#state
Reading 0:00
15s threshold

Hey!

Before we start — let me show you a problem.

You are building a simple counter. You use useState.

const [ count , setCount ] = useState ( 0 );

Enter fullscreen mode

Exit fullscreen mode

Works perfectly. No complaints.

Now the requirements change.

Your counter needs to:

Increment by 1

Decrement by 1

Reset to 0

Increment by a custom amount

Decrement by a custom amount

So you start adding more logic.

function increment () { setCount ( count + 1 ); }

function decrement () { if ( count > 0 ) { setCount ( count - 1 ); } }

function reset () { setCount ( 0 ); }

function incrementByAmount ( amount ) { setCount ( count + amount ); }

function decrementByAmount ( amount ) { if ( count - amount >= 0 ) { setCount ( count - amount ); } }

Enter fullscreen mode

Exit fullscreen mode

Five separate functions. All of them scattered around your component. All of them touching the same state in different ways.

Now imagine your component has 3 or 4 pieces of state — not just a counter.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.