React Key Concepts by Schwarzmüller Maximilian;

React Key Concepts by Schwarzmüller Maximilian;

Author:Schwarzmüller, Maximilian;
Language: eng
Format: epub
Publisher: Packt Publishing, Limited
Published: 2022-12-21T00:00:00+00:00


Revisiting Component Evaluations and Updates

Before exploring React's internal workings, it makes sense to briefly revisit React's logic for executing component functions.

Component functions are executed whenever their internal state changes or their parent component function is executed again. The latter happens because, if a parent component function is called, its entire JSX code (which points at the child component function) is re-evaluated. Any component functions referenced in that JSX code are therefore also invoked again.

Consider a component structure like this:

function NestedChild() {

console.log('<NestedChild /> is called.');

return <p id="nested-child">A component, deeply nested into the component tree.</p>;

}

function Child() {

console.log('<Child /> is called.');

return (

<div id="child">

<p>

A component, rendered inside another component, containing yet another

component.

</p>

<NestedChild />

</div>

);

}

function Parent() {

console.log('<Parent /> is called.');

const [counter, setCounter] = useState(0);

function incCounterHandler() {

setCounter((prevCounter) => prevCounter + 1);

}

return (

<div id="parent">

<p>A component, nested into App, containing another component (Child).</p>

<p>Counter: {counter}</p>

<button onClick={incCounterHandler}>Increment</button>

<Child />

</div>

);

}

In this example structure, the Parent component renders a <div> with two paragraphs, a button, and another component: the Child component. That component in turn outputs a <div> with a paragraph and yet another component: the NestedChild component (which then only outputs a paragraph).

The Parent component also manages some state (a dummy counter), which is changed whenever the button is clicked. All three components print a message via console.log(), simply to make it easy to spot when each component is called by React.

The following screenshot shows those components in action—after the button was clicked:



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.