useState and useEffect Hooks in React

Sashini Hettiarachchi
2 min readNov 7, 2020
Ref:: https://morioh.com/p/3671d1232dc6

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.

Wrapper Hell : Ref :- https://velog.io/@hyounglee/TIL-59
  • 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.

--

--