Using useState hook in React.js


Hooks allows the functional component in react to get the features available in class based component in make them more powerful.

useState we will import from react. Import {useState} from ‘react’; This helps us in creating local state variables for functional component and provides method to update that variable.

State in class is an object, but with useState we can create simple primitive data types and object if we want.

const test=()=>{
   const [age, setAge] = useState(25);
   return (
      <div>
         <p>Age: {age}</p>
         <button onClick={()=>setAge(age+1)}>Increase Age</button>
      </div>
   );
}

In the above example we created a state variable age which is initialized with 25. useState also provided us setAge method which we used on button click to increment age by 1.

The useState provides us an array with two elements 1. Current value 2. Function to update that value

The order of elements from useState is fixed that means first element is current value and second is set function.

Similarly we can create multiple state variable but these useState should be the first statement in your function body.

This is introduced in React 16.8 and its backward compatible that means we can convert the classes into functional components.

The useState initialize the variable only once in life of that component and maintains its value between multiple renders.

We can define an empty array.

const myList= useState([]);

we can pass previous value and process it in set function

setAge(preAge=>preAge+1);

while updating the value make sure to return a new object to trigger re-render else react assumes it as same object and wont re-render as explained below.

onClick={(e)=>{
   age.birthYear=e.target.value;
   setAge(age);
}}

It won’t trigger the re-render as we just mutated the current object and object remains the same.

Instead of this we should create new object.

onClick={(e)=>{
   const newAge={birthYear: e.target.value};
   setAge(newAge);
}}

The above way react sees the creation of new object and it will re-render on value change.

This approach clearly shows us that useState does not merge the updates but replaces them with new value. And setState in class based components merges them automatically .

To avoid the other properties of the object from getting lost we can use the spread operator

setAge((prev)=>{
   return {…prev, birthYear:newValue};
});

The spread operator will preserve the remaining properties the object from getting lost and also updates the other property.

Please note that all these hooks only works in functional component and never work in class based component. These hooks does not work in non react JavaScript functions.

These hooks should not be used in conditional statements or in loops but should be declared at the start of the function body in simple statements.

If you are more interested, analyzing code in class ReactFiberHooks of react library can be helpful where we can see the implementation of hooks.

Providing a initial value to local state variable is not necessary. Updates work in asynchronous way and does not block the UI from rendering.

Probably this the way the new modern react code will be written instead of writing classes.

Updated on: 04-Sep-2019

459 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements