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.
The local state in React is managed with the React.useState hook
Prerequisites: React - Getting Started (The Welcome Element)
With the createElement
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")
);
}
ReactDOM.render(
React.createElement(Counter, { user: "Foo"}),
document.getElementById('root')
);
An example written in React - JSX.
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>
);
}
ReactDOM.render(
<Counter/>,
document.getElementById('root')
);
This Jsx example shows you that the local state does not persist between mount (ie rendering).
We:
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>
);
}
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:
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.
React keeps track:
When you call a Hook like useState(), it:
It’s similar to this.setState in a class, except: