Reputation: 579
I am new to react.js, Below is my code
import React,{useState} from 'react';
import './App.css';
import Person from './Person/Person'
const App = props =>
{
const [personState, setPersonState] = useState({
persons : [
{name:"Max", age:28},
{name:"Manu", age:29},
{name:"Ranjeet", age:25}
],
otherState : 'Some state value'
}
);
console.log(personState);
const switchNameHandler = () =>{
setPersonState({
persons : [
{name:"Maximillian", age:28},
{name:"Manu", age:29},
{name:"Ranjeet", age:24}
],
otherState : personState.otherState
});
}
// function App() {
return (
<div className="App">
<h1>React App</h1>
<p>This is working</p>
<button onClick={switchNameHandler}>Switch Name</button>
<Person name={personState.persons[0].name} age={personState.persons[0].age}/>
<Person name={personState.persons[1].name} age={personState.persons[1].age}>My Hobbies:Racing</Person>
<Person name={personState.persons[2].name} age={personState.persons[2].age}/>
</div>
);
}
export default App;
Here i haven't console.log(personState) in switchNameHandler function, but it shows in console, When switchNameHandler is called, is that because of useState() hook or something else
{persons: Array(3), otherState: "Some state value"}
otherState: "Some state value"
persons: Array(3)
0: {name: "Maximillian", age: 28}
1: {name: "Manu", age: 29}
2: {name: "Ranjeet", age: 24}
length: 3
__proto__: Array(0)
__proto__: Object
Upvotes: 1
Views: 102
Reputation: 3020
Yes it’s because of useState.
In this code console.log will be called every time your App component is rendered.
This will at least be once when either the whole app is rendered, or any time your App components state changes. In your example, useState has created some state, and your click handler changes that state, so the App component is re-rendered.
Upvotes: 2