React Hooks

Md.Saiful Islam
4 min readMay 6, 2020

--

Hooks is a newest feature of React. Hooks were released in version 16.8, and they let us write stateful components without using the class syntax.

If you want to learn more about hooks, this guide is a simple introduction for you.Lets explore —

1)What is Hooks

React Hooks are functions that let us hook into the React state and lifecycle features from function components. It can easily manipulate the state of our functional component without needing to convert them into class components. Apart from that we can totally avoid using lifecycle methods, such as componentDidMount, componentDidUpdate, componentWillUnmount. Instead, we will use built-in hooks like useEffect .

2) Five Important Rules for Hooks

Before we talk about hook, let’s review a few of the major rules we must always follow.

  1. Never call Hooks from inside a loop, condition or nested function
  2. Hooks should sit at the top-level of your component
  3. Only call Hooks from React functional components
  4. Never call a Hook from a regular function
  5. Hooks can call other Hooks

3) Pros and Cons

Everything may has some positive as well as negative sides. React has made it easier to write a concise and clear code without any unnecessary elements to it. But, as it’s usually the case, all newly adopted functions or features, hooks have their pros and cons. Let’s look at some of them.

Pros

  • Simple and efficient
  • Easy to write, test and maintain
  • Allow creating re-usable components
  • Reduce nesting

Cons

  • Need to be applied correctly. In case of a mistake, it’s harder to trace it down and correct it, as hooks are called and realized in a stack system.
  • You can’t call on hooks in class-based components so introducing hooks into older projects is complicated and expensive as it requires rewriting a lot of the code. It only makes sense to use hooks in new projects.

So, as you can see, hooks can be a valuable asset in most React projects.

4) useState

useState returns a pair of values: the current state and a function that updates it. This is why we write const [count, setCount] = useState(). This is similar to this.state.count and this.setState in a class.

Example:

We call the useState Hook directly inside our component:

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

declares a state variable. The only argument 0 to the useState()Hook is the initial state.

5) Declaring multiple state variables

You can use the State Hook more than once in a single component:

function ExampleWithManyStates() {// Declare multiple state variables!const [age, setAge] = useState(42);const [fruit, setFruit] = useState('banana');const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);// ...}

The array destructuring syntax lets us give different names to the state variables we declared by calling useState. These names aren’t a part of the useState API. Instead, React assumes that if you call useState many times, you do it in the same order during every render.

6) useEffect

useEffect serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes, but unified into a single API.

Example:

Here at each time this functional component renders due to count change, it will execute useEffect hook function. In this instance it’ll perform side effect of manual DOM change by manipulating external element.

import React, { useState, useEffect } from 'react';function App() {  const [count, setCount] = useState(0);useEffect(() => {     document.title = `You clicked ${count} times`;  },[]);return (    <div>      <p>You clicked {count} times</p>      <button onClick={() => setCount(count + 1)}> Click </button>    </div>  );}

We can take a second parameter as optional to say for which state effect should handle.

7) useMemo

useMemo() is another method from the Hook API that helps to optimize performance. It memoizes and returns the same value for the expensive calculations if dependencies remain the same

import React, {useMemo} from “react”;function App() {const arr = useMemo(()=>["rakib", "sakib", "oni","piyas"],[]);return (<div className=”App”><div>{arr}</div></div>);}export default App;

8) useRef():

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.

const refContainer = useRef(initialValue);

9) Custom hook:

A custom hook is just a function that uses other hooks. Custom hooks allow you to create functionality that can be reused across different components. You can of course just have functions to reuse functionality, but hooks come with the advantage of being able to ‘hook’ into things like component lifecycle and state.

Example:

illustrate the power of hook composition that allow us to create a useDarkMode() hook.

// Usagefunction App() {const [darkMode, setDarkMode] = useDarkMode();return (<div><div className="navbar"><Toggle darkMode={darkMode} setDarkMode={setDarkMode} /></div><Content /></div>);}// Hookfunction useDarkMode() {const [enabledState, setEnabledState] = useLocalStorage('dark-mode-enabled');const prefersDarkMode = usePrefersDarkMode();const enabled =typeof enabledState !== 'undefined' ? enabledState : prefersDarkMode;useEffect(() => {const className = 'dark-mode';const element = window.document.body;if (enabled) {element.classList.add(className);} else {element.classList.remove(className);}},[enabled]);return [enabled, setEnabledState];}function usePrefersDarkMode() {return useMedia(['(prefers-color-scheme: dark)'], [true], false);}

10) Closure:

A closure is a function that remembers its outer variables and can access them. Whenever JavaScript executes a function, a ‘scope’ object is created to hold the local variables created within that function.

Example:

function makeAdder(a) {return function(b) {return a + b;}}x = makeAdder(5);console.log(x(6));

So when makeAdder() is called, a scope object is created with one property: a, which is the argument passed to the makeAdder() function. makeAdder() then returns a newly created function.

That’s all. Thanks for reading.

--

--

No responses yet