useState and useEffect Hooks in React

This article is an introduction of React Hooks and with a detailed explanation of useState and useEffect hooks.

Content of this article as follows,

  1. Why React Hooks?
  2. Rules of Hooks
  3. What are the basic React Hooks?
  4. useState Hook with examples
  5. useEffect Hook with examples

React Hooks?

In React 16.08 React Hook was introduced to solve some issues in using React classes. But Hooks didn’t have any breaking changes as well as it is related to previous react concepts like props, states, context etc.

Why React Hooks?

Because of three main reasons, React Hooks came to the picture. Those three reasons as follows,

  • Reusing logic

To share codes between two components in the class components we used rendering props for higher-order components (HOC)( a higher-order component is a function that takes a component and returns a new component. Ex: Redux connect). The downside of these two patterns is you have to restructure your application and it will cause Wrapper hell.

  • Giant component

When we are using class components they are getting larger because each individual task has to be split across different life cycle methods.

  • Confusing classes

Most of the people are confused when they are working with class components and class components are difficult to hot reload reliably.

Rules of Hooks

Only Call Hooks at the Top Level

React hooks cannot call inside loops, conditions, or nested functions.

Only Call Hooks from React Functions

You can only use React Hooks inside a React function and don’t use them in the regular JavaScript functions.

useState Hook

To manage states in the React component we are using useSate Hook.

1 — State variable

2 — Setter function

3 — useState Hook imported from React

4 — Initial State

import React, { useState } from ‘react’;
const Employee = () => {
const [name, setName] = useState(“Mary”);
const handleNameChange = (e) => {
setName(e.target.value)
}
return (
<div>
<h1>Employee Data</h1>
<input type=”text” name=”name” onChange={handleNameChange}> </input>
<h3>Name : {name}</h3>
</div>
)
}
export default Employee;

useEffect Hook

useEffect Hook is used to updating the component after loading that component to DOM. useEffect runs when the component is first rendered and on every subsequent update/re-render and this is a combination of componentDidMount, componentDidUpdate and componentWillUnmount in class components.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store