Lesson 1. Store a local state with useState 2. More about the initial state
As we saw, the parameter we give to useState is the initial value we want to
give to the state. This means that this value will be used only once, when the
component is rendered for the first time. For instance, let’s consider the
following example:
const Comp = ({ name }) => {const [uppercaseName, setUppercaseName] = useState(name.toUpperCase())// ...}
We could expect the state uppercaseName to be re-computed when the prop name
is updated; it is not. The only time uppercaseName is computed from name is
at the first rendering; then it has its own life, and the only way to update it
is to use setUppercaseName. We will see how to watch for the prop update using
the useEffect hook in the next lesson.
Note that another syntax exists to set the initial state: using a function.
const [value, setValue] = useState(() => {return makeSomeExpensiveCalculation()})
This signature exists because sometimes you will need to initialize the state
value with the result of some expensive calculation. We just said that
useState only considered the initial value during the first rendering, but it
doesn’t prevent JavaScript to evaluate the value if we don’t use a function:
const [value, setValue] = useState(makeSomeExpensiveCalculation())
Here the expression makeSomeExpensiveCalculation() will be evaluated even if
useState doesn’t use it; using a function as a parameter prevents this:
useState will call the function only if it needs to.
You probably won’t need to use this syntax very often, but it can be useful to know it if you see it in existing code or notice some performance issue regarding the initial value of a state.
Note that even if you can pass a function to compute the initial state, it
doesn’t mean that this function can trigger side effects. In particular, the
function can’t be asynchronous (i.e., return a promise). The rendering process
of a component must be synchronous and without any side effects. If you need to
call an API to get the initial value of a state, you’ll have to use the
useEffect hook, as we’ll see in the next lesson.