Getting Started with React Hooks — useState (Part-I)
As react 16.8 introduced new Hooks concept that lets you use state and other React features in functional based components.
React Hook
So lets first start with knowing what is React Hook?
A React Hook is a special function that lets you “hook into” React features. Hooks don’t work inside classes — they let you use React without classes. For Example, useState is a Hook that lets you add React state to the functional based components.
React provides few built in hooks like useState, useEffect and also allows us to create our own hooks. In this part we will learn about using useState in react. In coming part we learn about remaining two.
When to use Hooks?
If you need to add state or other React features to a functional component, you can make use of react Hooks.
Now lets dive deeper into useState hook.
Understanding useState Hook
useState is a react hook that is used to store and manipulate the state of the functional component.
Now that we understood about hooks. Lets see it in practice; Let us start by creating a hello world react application using react hooks
You have to always write useState at the top of the function, before writing anything else in the function body. The only argument that useState takes is the initial state of the variable.
In this example, we have created a nameState constant variable which holds the state of the component (that is nothing but “Hello World!”).
useState returns an array that is stored in nameState variable. The array returned by useState has exactly two elements, the first element is current state and the second element is the function that you can use to manipulate the state. You can access these two methods by using array indexes. (For Example: nameState[0], which gives you current state, and nameState[1], which gives you function that can be used to manipulate the state).
Dynamic useState Hook
Now lets manipulate the current state with what user enters in the text field.
Here we are updating the state of nameState variable, using the second element of the array that the useState returns to the event.target.value and that is hooked with the onChange of the <input /> tag.
Using Multiple useState Hooks
Single component can have more than one useState variables in the function as shown below.
Key takeaways:
- React Hooks are special function that lets you incorporate React features in functional based components
- React provides three types of hooks, viz; useState, useEffect and custom hooks (or user created hooks)
- useState is a react hook that is used to store the state of the component or user
- Single functional component can have more than one useState variables
References:
- React docs: https://reactjs.org/docs/hooks-overview.html
- Udemy react course: https://www.udemy.com/react-the-complete-guide-incl-redux/