Search code examples
reactjsfrontendtheory

Some help realizing the flow of code operations in react or web rendering in general


Say I'm writing a simple button in react. The button will display some text onclick and remove it afterwards:

export default function Button(){
    const [isShown, setIsShown] = React.useState(false);

    const handleClick = event => {

        setIsShown(current => !current);

    }

    return <div>
        <button onClick={handleClick}> click</button>
        {isShown && (
            <div>
                content
            </div>
        )}
    </div>
}

I'm a relatively new coder, and when I see code I expect it to run from top to bottom. But every time I click the button on the webpage the content is shown or removed. So my guess is that the part that decides to render the content is run constantly or at least each time the button is clicked.

What is the flow of code operation? Does activating an onClick event cause a full running of all JSX code? If not, how are the affected parts rerun? Are there any resources you can recommend which will illuminate the flow?


Solution

  • In short, your React component will re-render every time the state of your component changes. So in your case, when you call your handler, the built-in hook useState() will trigger a render and whatever is in your isShown will be updated to the screen.

    Here is a link to the React documentation where you will find what render actually means. You will also learn about the life cycle of a React Component and how JSX behaves.

    https://react.dev/learn/render-and-commit

    If you are wondering what state means in React, the best way to think about it is that the state is the memory of your component :

    https://react.dev/learn/state-a-components-memory