Sobes.tech
Junior — Senior

Resetting the counter when switching pages

livecode

Task condition

It is necessary to change the behavior so that each time the "toggle page" button is pressed, the internal counter of the Counter component resets to zero. Currently, the counter value is stored in the child component and persists when the page property changes, so it is necessary to add logic to reset the state using React hooks.

import React, { useState, FC } from "react";

const ClickInfo: React.FC<{ clicks: number }> = ({ clicks }) => {
    return <p>Clicked: {clicks}</p>;
};

export const Counter = () => {
    const [clicks, setClicks] = useState(0);
    const increase = () => {
        setClicks((prev) => prev + 1);
    };

    return (
        <div>
            <button onClick={increase}>Click me!</button>
            <ClickInfo clicks={clicks} />
        </div>
    );
};

const Page: FC<{ page: string }> = ({ page }) => {
    return (
        <div>
            page: {page}
            <Counter />
        </div>
    );
};

export const SwitchView = () => {
    const [currentView, setCurrentView] = useState<"one" | "two">("one");

    return (
        <>
            <button
                onClick={() =>
                    setCurrentView((prev) => (prev === "one" ? "two" : "one"))
                }
            >
                toggle page
            </button>
            <Page page={currentView} />
        </>
    );
};
``