Cyan Coder
Cyan Coder

Reputation: 87

Why i get infinity loop when i update object by setState?

Im trying change class name by using library classname. And i got problem when update my object data for save state of className. I am sure not problem with library classname. Some one can help me ?

    export default function Sidebar() {
    const [active, setActive] = useState({
        home: false,
        category: false,
        product: false,
        order: false,
    });
    const handleActive = (name) => {
        setActive({
            ...active,
            [name]: !active[name],
        });
    };
    return (
        <Col md={2} id="sidebar">
            <ul>
                <li className={classNames({ active: active.home })} onClick={handleActive("home")}>
                    <NavLink to={`/home`}> Home </NavLink>
                </li>
                <li className={classNames({ active: active.category })} onClick={handleActive("category")}>
                    <NavLink to={`/category`}> Category </NavLink>
                </li>
                <li className={classNames({ active: active.product })} onClick={handleActive("product")}>
                    <NavLink to={`/product`}> Product </NavLink>
                </li>
                <li className={classNames({ active: active.order })} onClick={handleActive("order")}>
                    <NavLink to={`/order`}> Order </NavLink>
                </li>
            </ul>
        </Col>
    );
}

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

Upvotes: 0

Views: 86

Answers (1)

Prateek Thapa
Prateek Thapa

Reputation: 4938

PROBLEM

You're calling the function directly here onClick={handleActive("order")} which triggers the multiple re-renders. What you're saying to the code here is let's call the onClick handler whenever the component mounts.

SOLUTION

() => handleActive("home") assign a function to the onClick handlers like this. What you're saying to the code here is I'm assigning a function to the onClick handlers, call the function whenever someone clicks on the element.

<li className={classNames({ active: active.home })} onClick={() => handleActive("home")}>
    <NavLink to={`/home`}> Home </NavLink>
</li>

Upvotes: 1

Related Questions