About
This page is about the local state (known as the state in react) in a React Functional Component.
In this context, the state is managed by the useState hook.
Example
The local state in React is managed with the React.useState hook
Prerequisites: React - Getting Started (The Welcome Element)
Native
With the createElement
- The component
function Counter(props) {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = React.useState(0);
return React.createElement(
'div',
null,
React.createElement("p", null, props.user, " clicked ", count, " times"),
React.createElement("button", { onClick: () => setCount(previousCount => previousCount + 1) } , "Click Me")
);
}
- The rendering part
ReactDOM.render(
React.createElement(Counter, { user: "Foo"}),
document.getElementById('root')
);
- Result:
Jsx
An example written in React - JSX.
- The component
function Counter() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = React.useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
- The rendering part
ReactDOM.render(
<Counter/>,
document.getElementById('root')
);
- Result:
Important: State does not persist on component Mount
This Jsx example shows you that the local state does not persist between mount (ie rendering).
We:
- Use the same previous counter example
- and show or cache it (mount/demount) via a button
Example:
function App(){
const [show, setShow] = React.useState(1);
let counter;
if(show){
counter = <Counter/>;
}
return (
<div>
<button onClick={()=>setShow(!show)}>{show? 'Demount the counter' : 'Mount the counter'}</button>
{counter}
</div>
);
}
- Result:
- Click on the counter button to increment the counter,
- Cache the counter and show it again with the mount button
- You will see that the counter is back to 0
Syntax
Single
Normally, variables “disappear” when the function exits but React will preserve the state between re-renders.
const { currentValue, setValue } = useState(initialState);
// or
[<getter>, <setter>] = useState(<initialValue>)
where:
- initialState is:
- the only useStateargument and define the initial state.
- only used during the first render.
- useState returns a pair:
- currentValue, the current state value
- setValue is a function that lets you update the value and trigger a render. It accepts:
- a single value
- a function where the first argument is the previous state
Multiple
Declaring multiple state variables is just a question of copying the declaration line
const [age, setAge] = useState(42);
const [fruit, setFruit] = useState('banana');
const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
There is no use of name for state identification, the order is then important ! React assumes that if you call useState many times, you do it in the same order during every render.
How multiple useState() calls each get independent local state ?
React keeps track:
- of the currently rendering component.
- of the state with an an internal list of “memory cells” (object) (associated with each component).
When you call a Hook like useState(), it:
- reads the current component
- reads or create a component cell
- moves the pointer to the next cell.
useState versus setState
It’s similar to this.setState in a class, except:
- it doesn’t merge the old and new state together.
- updating a state variable always replaces it instead of merging it.
- the state doesn’t have to be an object