UseState in React: An overview
Hooks have come to play a major role in React component development, specifically in functional components as they have completely replaced the need for class-based components, which was initially the traditional go-to method for creating components that required states or handling life-cycle methods or side effects. React Hooks are a new feature addition in react version 16.8 which allows you to use react features without having to write a class for example the condition i.e. (state) of a react component.
What is a Hook?
A hook is a special function that allows a developer to connect to react features. E.g. useState is a hook lets one add React state to function components. A state is a JS object used by react to represent an information about the component's current situation that is privately maintained inside a component, which influences what is rendered on the browser and allows for changes within the component, It also allows us manage changing data in an application. Amongst the several hooks introduced, the useState hook is easily one of the most important hooks. However, it can be very tricky to understand, especially to newer React developers just getting into React or migrating from class-based components to function components. In the case of managing data in a state, one might want to modify either a user data or some sort of property in the state using an event handler which in turn updates the state data, previously we couldn’t add state to functional components in react except they are transformed to class components. But the introduction of react hooks has made it possible through: useState () .
What is a the useState () Hook?
useState (): It is a react hook that returns a pair of values which are the initial value and a function that updates the it. Code Sample.
import React , { useState } from 'react';
const UseStateBasics = () => {
const [text, setText] = useState('random-title');
}
Breaking down the syntax; We call the useState function and pass a default value as argument which returns an array comprises of the default value and our updater function. The initial value can be a string, Boolean or of any datatype. The text is the variable that will store our value and setText is the function that is responsible to update the text. For updating the value in the state we make use of an event which triggers the function to return a new value which is different from our default value.
<button className='btn' onClick={handleClick}>
Change Text
</button>
At the instance the button is triggered it re-renders the text and returns a new text value.