What is the useState in React?useState() hook in React is a hook that allows us to state variables in our functional components. React has two types of components. The first one is class components which are ES6 classes that extend from the React, and the second one is functional components. Class-to-components will have state and lifecycle methods: the message class extends React. useState Hook is a special function which takes the initial state as the arguments and returns it as an input array. Syntax: The first element is the initial state, and the second one is a function used to update the state. We pass a function as an argument if the initial state is computed. And the return value of the function is used as the initial state. The above function is the line function which calculates the sum of numbers and it set as the initial state of it. To use useState, we need to import useState from the react as given below: useState() is a built-in function which comes by the React library. useState() is only used inside a functional component. useState() cannot work on class component. useState() returns a tuple. The parameter of the array is the current state of value. The second parameter is the function that allows updating the value of the state. React useState() exampleCreating the React app:Step 1: Create a React app by using the command below: Step 2 After creating the project, i.e., folder name, access it by the command or syntax below: The implementation of the use State () function Application.js: Step to run the application: Run the application by using the command from the root directory of the project: A random number initializes the first count variable to use a random function and setRandomCount to update the count state. Whenever we click the onClick button, it calls the click Handler function, which resets the count variable by a random number. React's UseState Hook allows tracking the state in a function component. State refers to data that needs to be tracked in the application. We first import it into our component to use useState Hook. Initialize useStateWe initialize our state by calling the use State on the function component. useState accepts the initial state and returns the two values which are given below:
Example 1:Initialize the state at the top of the function component. Notice that we are destructuring the return values of useState.
Now we can include state anywhere in the component. Example 2:Use the state variable in rendered component. Output: Update StatusWe use our updated status feature to update status. We can never directly update the state. E.g., color = "red" is not allowed here. Example 3:Output: After clicking on the blue button, it turns blue like the below: What Can State Hold?UseState Hook is used to keep track of Strings, Like Numbers, Booleans, Arrays, Objects, and other combinations of these. We create multi-state Hooks to track individual values. Example 4:Output: You can use a state and include an object instead! Example 5:Create a single Hook that will holds an object: Output: Since we are tracking a single object, we need to reference the object and the object's property rendering the component. When the state is updated, then the entire state is overwritten. What if we update the color of the car?If we called setCar({color: "blue"}), it removes the model and year from the state. We use the JavaScript spread operator for this. Example 6:Here, we are using the JavaScript spread operator to update the color of the car: Output: Here, we need the current value of the state, where we pass a function to the setCar function. The function receives the previous value. We return an object, extending the state and overwriting only the car's color. React provides many hooks that allow to addition functionality of the components. These hooks are JavaScript functions that can import from the React package. However, hooks are available for function-based components, so they cannot be used inside a class component. What is useState, and when do we use it?React provides many hooks that we can use in our application. useState and useEffect are the two important hooks that we use a lot. UseState is a function that takes only one argument at a time, the initial state, and it returns two values: the current state and a state case. If we print the useState() function in the React dev tools (console.log(useState)), we notice that it returns an array containing the argument that you have put in the useState function. UseState Hook is used when you want to change the text after clicking a button, like creating a counter. Simple examples of useStateYou first must import it from the React package to use the useState Hooks. Here is an example: Now, you can start using the Hook in the code without any problem. See the following example: Note that we are using here the unstructured ES6 array in the component. So, the variable's name inside the array refers to the argument of the function useState. On the other hand, the setName variable refers to the function you add to update the state. We have a state name and call the setName() function. Let's use it by the return statement: Since function components do not have a setState() function, you must use the setName() function to update it. It is how he changes the name from "Brad" to "John": Multiple-use stateYou can call useState Hook as much as you need when you have many states. Example: The hook receives all javaScript boolean, data types, such as string, number array, and object. Here we will cover the basics of React.useState(). What is UseState Hook?In React, functional components are stateless as we cannot manage their state. If we write a component when we need to add some state to it, you can use useState Hook with React 16.8. useState allows to add of the React state of the running components.
It's similar to this.state.count and this.setState in a class, except we see them in a pair. The useState() Hook is the initial state of Hook. The state does not have to be an object. Below is the code snippet for a counter that uses a class component. We want to implement a similar counter into the functional component. Import the useState Hook from the React AppDeclare a new state variable by calling the useState Hook. Returns a value pair, counterValue, with the number of clicks and setCounter, that updates the counter value. Initialize counterValue to zero by passing zero as the useState argument. When the user clicks on setCounter with a new value, react will re-render the component and pass in the new value of the counterValue. ConclusionThe useState Hook is one of the necessary and useful hooks we should know about. Also, it allows function components to do their internal state and features. Next TopicReact Time-Picker |