React Hooks

Javad Shahkoohi
2 min readAug 15, 2019

--

ES6 classes in React won’t go away anytime soon. But now with React hooks it’s possible to express the flow internal state change. Then UI reactions without using an ES6 class.

Most important React Hooks

React hooks were born for a reason: sharing logic between components (a nice, standardized, and clean way for encapsulating and sharing logic.)

  1. useState: useState is a function exposed by the react package.
  • Import the function: import React, { useState } from "react";
  • By importing useState in code, signaling the intent to hold some kind of state inside your React component. It is important, that React component shouldn’t be an ES6 class anymore. It can be a pure and simple JavaScript function.
  • Afterward, pick an array containing two variables out of useState. const [buttonText, setButtonText] = useState("Click me, please");

Advise: using descriptive and meaningful variable names depending on the state’s purpose.

  • argument passed to useState is the actual starting state
  • useState returns for you two bindings: first: the state updater function for said state. second: the actual value for the state

2. useEffect: could be the right tool for fetching data. useEffect serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes, but unified into a single API.

  • The component becomes a function and fetch gets called inside useEffect. Moreover, instead of calling this.setState you can use setData (an arbitrary function extracted from useState).
  • componentDidUpdate is a lifecycle method running every time a component gets new props, or a state change happens. Then, if you call useEffect, you would see an infinite loop and for solving this “bug” you would need to pass an empty array as a second argument to useEffect.
useEffect(() => {
fetch("http://localhost:3001/links/")
.then(response => response.json())
.then(data => setData(data));
}, []); // << super important array, or [count]); Only re-run the effect if count changes
  • No return a Promise from useEffect. JavaScript async functions always return a promise and useEffect should exclusively return another function, which is used for cleaning up the effect.

Benefits of Hooks:

  • Separation of JavaScrit logic and HTML-DOM elements, by passing a render function as a props.
  • Instead of HOCs and render props, we can encapsulate our logic in a React Hook and then import that hook whenever we feel the need. For example,creating a custom hooks for fetching data.
// use_fetch.js
import { useState, useEffect } from "react";
export default function useFetch(url) {
const [data, setData] = useState([]);
useEffect(() => {
fetch(url)
.then(response => response.json())
.then(data => setData(data));
}, []);
return data;
}
// data_loader.js
import React from "react";
import useFetch from "./useFetch";
export default function DataLoader(props) {
const data = useFetch("http://localhost:3001/links/");
return (
<div>
<ul>
{data.map(el => (<li key={el.id}>{el.title}</li>))}
</ul>
</div>
);
}

Rules of Hooks

  • Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.
  • Only call Hooks from React function components. Don’t call Hooks from regular JavaScript functions

[1]. https://reactjs.org/docs/hooks-state.html

[2]. https://www.valentinog.com/blog/hooks/

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response