Understanding React Hooks ⚛️

Understanding React Hooks ⚛️

Let's Learn about React Hooks

We can build Components in React by writing functions. UI Components are often dynamic , they may need to change the state of the data , react to the lifecycle events, access elements from the DOM among many other things. React Hooks generally provide more ergonomic way to build components because we use can reuse logic without changing your component hierarchy.

Some of the React Hooks are as follows

  • useState

React Hooks can be called at the top level of the Functional Component. They don't work inside a regular JavaScript Functions, nested functions , loops etc.

Screen Shot 2021-05-28 at 10.56.36 PM.png

useState()

useState is the most important and often used hook. To import in your React App type useState in App.js it directly import from React. The purpose of useState() is to handle reactive data. Any data that changes in the application is called State and when the state changes you want react to update the UI so the latest changes can be reflected to the enduser.

Screen Shot 2021-05-28 at 11.02.11 PM.png

import { useState } from 'react';

function App() {

    const [count, setCount] = useState(0);

    return (<button onClick= {()=> setCount(count+1)}>

              {count}

         </button>);
}

Here count is the reactive data or state , setCount is the setter through we can set the new value to count. If we then reference it in the UI and if the value changes in the future React will automatically re render the UI to show the latest value. It will show 0 by default. On onClick event on the button using setCount function we can increment the count by 1.

That's It For Now. See You In Next One ✌️