EN
React - useState example (functional component)
3 points
In this article, we would like to show you simple useState
example in React functional component.
Below example shows how to make a simple counter
which is being incremented every button
click action.
In the App
component we create useState
hook, which keeps the state
of our component inside a counter
. It is very important to use hooks at beginning of components - that is main React rule.
To update the counter
we use setCounter
function, passing counter + 1
as new state - it causes App
component re-rendering with new state.
Runnable example:
xxxxxxxxxx
1
//Note: Uncomment import lines during working with JSX Compiler.
2
//import React from 'react';
3
4
const App = () => {
5
const [counter, setCounter] = React.useState(0);
6
return (
7
<div>
8
<div>Counter: {counter}</div>
9
<button onClick={() => setCounter(counter + 1)}>add 1</button>
10
</div>
11
);
12
};
13
14
const root = document.querySelector('#root');
15
ReactDOM.render(<App />, root );
It is possible to keep state inside nested components too. It works the same way - requires to use only useState()
function.
Check below example to see how it works:
xxxxxxxxxx
1
//Note: Uncomment import lines during working with JSX Compiler.
2
//import React from 'react';
3
4
const ChildComponent = () => {
5
const [counter, setCounter] = React.useState(0);
6
return (
7
<div>
8
<span>[ChildComponent] Counter: {counter}</span>{' '}
9
<button onClick={() => setCounter(counter + 1)}>add 1</button>
10
</div>
11
);
12
};
13
14
const App = () => {
15
const [counter, setCounter] = React.useState(0);
16
return (
17
<div>
18
<div>
19
<span>[App] Counter: {counter}</span>{' '}
20
<button onClick={() => setCounter(counter + 1)}>add 1</button>
21
</div>
22
<ChildComponent />
23
</div>
24
);
25
};
26
27
const root = document.querySelector('#root');
28
ReactDOM.render(<App />, root );