state;
react is based on components
Each component has props
props are read only values passed into a component from a parent
each component also has its own state.
...used to store values local only to that component that store data that is going to change
state is ...
...used to store values, that when updated re-render the component
state is ...
...immutable. When you update the data, you are not changing the value, you are replacing the old data with the new data
state is ...
hooks
new as of spring 2019
but first...
Destructuring assignment
const arr = [10,12,13,14]
const [first, second] = arr
const first = arr[0]
const second = arr[1]
console.log(first) // will log out 10
console.log(second) // will log out 12
// Bonus:
const [firstValue, secondValue, ...theRest] = arr
const firstValue = arr[0]
const secondValue = arr[1]
const theRest = arr.slice(2)
simple example
basic state
const Person = () => {
const [cupsOfCoffee, setCupsOfCoffee] = useState(0)
return (
<div>
<h1>Good Morning!</h1>
<h2>I have had {cupsOfCoffee} today.</h2>
</div>
);
}
updating a hook
const Person = () => {
const [cupsOfCoffee, setCupsOfCoffee] = useState(0)
return (
<div>
<h1>Good Morning!</h1>
<h2>I have had {cupsOfCoffee} today.</h2>
<button onClick={() => setCupsOfCoffee(cupsOfCoffee + 1)}>drink</button>
</div>
)
}
intro-to-hooks-as-state
By Mark Dewey
intro-to-hooks-as-state
- 227