Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Too many re-renders in react when using useReducer Hook

I'm facing a weird problem when using the useReducer react hook, I know the origin of the error, but I don't know why it occurs in my code.

import React, { useReducer } from 'react'

import { Button } from 'react-bootstrap'


export default function User() {

const initialState = {
    lowScore: 0,
    mediumScore: 0,
    hightScore: 0 
}

const reducer = (state, action) => {
    switch(action.type){
        case 'LOW':
            return {
                ...state,
                lowScore: state.lowScore + 1
            }
        case 'MEDIUM':
            return {
                ...state,
                mediumScore: state.mediumScore + 1
            }
        case 'HIGH':
            return {
                ...state,
                hightScore: state.hightScore + 1
            }
        default:
            return state
    }
}

const [state, dispatch] = useReducer(reducer, initialState)

return (
    <div>
        Low: { state.lowScore }, medium: { state.mediumScore }, hight: { state.hightScore } 
        <Button onClick={dispatch('LOW')}>Increment low</Button>
        <Button >Increment medium</Button>
        <Button >Increment hight</Button>
    </div>
)
}

I dispatch the action only when the user click on the buttons, so I can't figure out how it causes multiples renders.

Any explanation would be precious

like image 763
Lyes Avatar asked Dec 06 '25 06:12

Lyes


1 Answers

When you render component. You have called function dispath without any click. You should pass a call back to event onClick:

Updated correctly action make it work:

   <Button onClick={() => dispatch({type: 'LOW'})}>Increment low</Button>
like image 161
Viet Dinh Avatar answered Dec 07 '25 19:12

Viet Dinh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!