React infinite loop

Hi, When I’m trying to render the following component I’m getting the error showing too many re-renders. Here is the component

import React, {useState, useContext, useReducer} from "react";

const mealItems = [

    {

        name:"banana",

        id:Math.random()*5,

        origin:"india",

        price:45

    },

    {

        name:"apple",

        origin:"australia",

        id:Math.random()*5,

        price:92

    },

    {

        name:"orange",

        origin:"usa",

        id:Math.random()*5,

        price:134

    }

]

const cartItems = [];

function Input (){

    let initialState = 1;

    const reducer = function (state, action){

        if(action.type === "substract"){

            if(state<0){

                return;

            }

            else{

            return (state)=>state-=1;

            }

        }

        else if(action.type=== "add"){

            return (state)=>state+=1;

        }

    }

    const[state, dispatchFunction] = useReducer(reducer, initialState);

    return (

        <>

        <button onClick = {dispatchFunction({type:"substract"})}>substract</button>

        <input type = "number" value = {state}/>

        <button onClick = {dispatchFunction({type:"add"})}>addition</button>

        </>

    )

}

Please help

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Your component is invoking dispatchFunction whenever it runs. Wrap the calls to dispatch inside a function () =>

Your reducer is not correct. It should return the new state, or the old state or throw, and it shouldn’t mutate the state (return state + 1 or return state - 1).

You have a controlled input without an onChange handler.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.