The Opinionated Guide to React 02 - On state management
On useState, Context and others
useState permalink
- for handling local state (on a component level)
Global state with Context permalink
for many use cases where you need state spread around your application (but the state is not too complex)
Context
: provides us with two components: aProvider
and aConsumer
.Provider
: holds the valuesConsumer
: reads the values (viauseContext
hook)
🕵️♀️ Example:
import React, { useContext } from "react";
const Person = {
name: "Sara",
city: "Berlin",
nationality: "Portugal",
};
const PersonContext = React.createContext();
const Header = () => {
const person = useContext(PersonContext);
return <p>Hello {person.name}</p>;
};
const Main = () => {
const person = useContext(PersonContext);
return (
<p>
I see with you are from {person.nationality} and live in {person.city}
</p>
);
};
const App = () => {
return (
<PersonContext.Provider value={Person}>
<>
<Header />
<Main />
</>
</PersonContext.Provider>
);
};
export default App;
State Management Library permalink
To be discussed later in a separate chapter