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:
// ONLINE-RUNNER:browser;
//Note: Uncomment import lines during working with JSX Compiler.
//import React from 'react';
const App = () => {
const [counter, setCounter] = React.useState(0);
return (
<div>
<div>Counter: {counter}</div>
<button onClick={() => setCounter(counter + 1)}>add 1</button>
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root );
Use state in child components example
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:
// ONLINE-RUNNER:browser;
//Note: Uncomment import lines during working with JSX Compiler.
//import React from 'react';
const ChildComponent = () => {
const [counter, setCounter] = React.useState(0);
return (
<div>
<span>[ChildComponent] Counter: {counter}</span>{' '}
<button onClick={() => setCounter(counter + 1)}>add 1</button>
</div>
);
};
const App = () => {
const [counter, setCounter] = React.useState(0);
return (
<div>
<div>
<span>[App] Counter: {counter}</span>{' '}
<button onClick={() => setCounter(counter + 1)}>add 1</button>
</div>
<ChildComponent />
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root );