state is some information you want to retain over time. it’s the stuff you want the computer to remember.
when you introduce a new piece of state into the program, you want to somehow tell the computer how long this information should be remembered. when is it ok to forget?
when you declare a state variable, you choose its lifetime — it “lives” for as long as the associated component is in the tree.
for example, a comment widget under a post might use state to store what you’re typing — but if you go to another page, the widget will unmount, and its state will go poof
component state is tied to a particular instance of the component in the tree — a “box on the screen”, if you will
for example, if some screen displays several posts, and each of those posts has an AddComment widget below, these widgets will stay completely independent from each other
if I lift my state up so much that it's now available to all my components, could it be considered global? for example, shouldn't my app theme be considered a global state?
Comments
when you introduce a new piece of state into the program, you want to somehow tell the computer how long this information should be remembered. when is it ok to forget?
function sayHello() {
let yourName = prompt("What's your name")
alert('Hello, ' + yourName)
}
it is an ephemeral piece of state — the yourName variable “disappears” as soon as the sayHello function exits. by then it has fully served its purpose
very often you’d want to associate a piece of state with something that appears on the screen.
in react, you do this by declaring a state variable in your component
function Greeting() {
const [yourName, setYourName] = useState('')
// ...
}
for example, a comment widget under a post might use state to store what you’re typing — but if you go to another page, the widget will unmount, and its state will go poof
for example, if some screen displays several posts, and each of those posts has an AddComment widget below, these widgets will stay completely independent from each other