16
loading...
This website collects cookies to deliver better user experience
React Component
. A part of life on Earth. But it goes through various phases. We know each as a season.state
.State is similar to props, but it is private and fully controlled by the component.
Props
themselves are Objects
. Their keys
are the name of the attributes
we pass to the component through JSX
. And their values
are that of the corresponding attributes.Object
, a String
, or any other JavaScript Type
. But what is the main difference between a state and a prop
? component
receives props
from its parent, while it creates and controls
its own state
.Nature
. This component has a main state variable: season
. First let's declare it just using a simple JavaScript variable
:function Nature(props) {
let season = 'spring';
return(
<p>Currently it is {season}</p>
)
}
const season = 'spring';
is where we declared our state variable. The output HTML looks like this:<p>Currently it is spring</p>
onClick
event a callback which will try to change the variable season
's value to 'summer':function Nature(props) {
let season = 'spring';
const changeSeason = () => {
season = 'summer'
}
return(
<div>
<p>Currently it is {season}</p>
<button onClick={changeSeason}>Click to change season!</button>
</div>
)
}
onClick
will never result in a change in the output.React Hooks Flow
. This is where things get interesting.Components Hook Flow
.Mount
, Update
and Unmount
.useState
and useReducer
initializer functions. Then it will continue the rest of the codes you have added in your functional component, up until it reaches the returned value. layoutEffects
which you create using the useLayoutEffect
hook. Then the browser paints the screen to reflect the React Virtual DOM. Then the effects
which you have registered using useEffect
are called.value change
, or when the input is blurred
.useState
hook to bring states to functional components. To initialize a state you need to call the hook and pass it the state's initial value
.state's value
and the second element is the state-setter function
.changeSeason
function to use the state-setter
function returned by useState
.function Nature(props) {
let [season, setSeason] = useState('spring');
const changeSeason = () => {
setSeason('summer')
}
return(
<div>
<p>Currently it is {season}</p>
<button onClick={changeSeason}>Click to change season!</button>
</div>
)
}
summer
.season
refers to the first element returned by useState which holds the latest state value. And setSeason is the method we can use to update the state's value.