Hello everyone. In this series, I will be giving you information about the hook structures of React, a javascript library. At the same time, while learning these hooks, we will be reinforcing them with examples. Without wasting any time, let’s start with the first hook structure, useState.
What is UseState?
Before starting useState, it is very important to know the concept of state. State is a structure that expresses data or properties that should be tracked in an application. In other words, just as we use structures like var-let-const to define a data in javascripts, we use the state structure in react.
UseState is a hook that you can provide state management used in react hook structure. It is very simple to import into the created component.
import React, { useState } from 'react';
The only argument UseState takes at startup is state. But it does not have to take a default value. If not entered, the state value will be NaN. Let’s continue with a small example from the React documentation.
UseState Example
import React, { useState } from 'react';
function App() {
// A new state variable is created, we will call it "count". We are going to count. :)
const [count, setCount] = useState(0);
// count : State value.
// setCount : It is a function structure where we can change the value of State..
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
count : The tool that gives the current state value.
setCount : It is a function structure that allows us to affect and change the value of State in.
Above we have created a useState named count. With the onClick event on the button in Return, we have set the counter value to increase by 1 on each click. We initially set the useState() value, that is, the count value, to 0. As I said, if we did not give a value, the result would return as NaN on each click.
In this article, we learned about useState, a hook tool in react. See you in my next blog post about useEffect, the next hook tool…
Source: React Docs