Understanding React Hooks

Deepak Mankotia
2 min readApr 4, 2020

--

Hooks are the functions which allow to use the state and react life cycle features from functional components. Hooks are introduced by React in 16.8 version.

Hooks let you manage state and other React features without creating class.

Let’s understand hook by finding the answer of below questions.
Why we need hooks?
What problem does hooks solve?

Hooks are used in functional component, before react version 16.7 or less if certain component have to manage state or use any react life-cycle method then we can not do that in functional components and it had to convert to class component. So to overcome this problem React team purpose hooks in ReactConf 2018.

State Hook
Using useState hook we can manage the state in functional component.

Here useState is a hook which allow us to manage the local state in functional component. useState return a pair which include a current state value and function which let you update the state. We can call this function on event and update the state. This is similar to this.setState in class component, except useState doesn’t merge new and old states together.
In above piece of code we have a functional component which has count state, count has default value 0 and on the button click setCount function increment the count by 1.

We can declare the state variable more than once in component.

Effect Hook

useEffect hook allow us to use side effects from functional component. Here “side effects ” means performing data fetching, subscriptions, or manually changing the DOM. useEffect works similar ascomponentDidMount, componentDidUpdate, and componentWillUnmount in class component.

Here useEffect hook is use to set the document title, useEffect has to arguments function and array. If you want to execute the function then skip the second argument other wise add the variable in array on which you want to execute the function, Like in above piece of code useEffect function will execute every time count value updated. We can use useEffect hook more than once and these are executed in the same order in which they added in component.

We can also create custom hooks.

Before binding up in short Hooks provide functionality to manage state and use React lifecycle. React hooks is not the replacement of classes.

Happy Coding!!

More articles
Useful Javascript Array trick which one should know
What is event loop in javascript?
How to start with GraphQL?
what is closure in javascript, advantages and disadvantages?

--

--