useState() Hook in React TypeScript
Prerequisites
- Make sure you have installed Node.js version 16+.
- To follow along with this article, you’ll need a react project that is generated with Nx. If you haven’t done it yet, see this article.
You can still follow the article by creating components in your own way.
Managing state with useState()
We can use the useState()
hook to set and manage some state that is tied to the component. To demonstrate this, let’s create a component called Username
. Run the following command to generate the component.
nx g c username --dir app/components
Open username.tsx
and write the following code.
At line number 7, we declared the username
state by using array destructing and assigned with useState()
. We can initialize the value by passing to the argument of the useState()
as below.
const [username, setUsername] = useState('');
(or)
const [username, setUsername] = useState('John');
We print out the current value of the usename
at line number 20.
At line number 10, you can see that user entered value is set to the username
state by using the setUsername()
method. The method is provided by the useState()
hook.
Note that when we call
setUsername()
method, React will re-execute the whole component by calling the component function. And re-declare theusername
state with the latest value. That’s why we can useconst
while declaring theusername
state.
Call from App Component
Open app.tsx and write the following code.
Serve the Application
Run with nx serve
and type your name in the input box.
Done
This is the simplest usage of useState()
hook. If you want to know more, please visit to official documentation here.