Home Education Fundamentals of React Hooks in 7 minutes by Prakash Mandal

Fundamentals of React Hooks in 7 minutes by Prakash Mandal

0
Fundamentals of React Hooks in 7 minutes by Prakash Mandal

Hooks have been really gaining a lot of popularity from the first day of its release by the Facebook React team. If you have any experience with class components then you can really understand how hooks make a React developer’s life easier. Lots of libraries like VueSvelte are adopting hooks to extends their features.

But on the other side, there is a lack of clarity about its uses. So, with the help of this article, I will try to make things easier to understand for you.

What are Hooks?

Hooks are a new addition to React 16.8. They let you use state and other React features without writing a class.

Contents

  1. Basic Hooks

2. Additional Hooks

3. Custom Hooks

Let’s go through all these hooks one by one.

Basic Hooks

useState

It is the most common hook in react which creates the state variable in a functional component.

const [state, setState] = useState(initialState);

To use it you can pass any value or function as an initial state and it returns an array of two entities, the first element is the initial state and the second one is a function (dispatcher) which is used to update the state.

import React, { useState } from 'react';

const HellComponent = (props) => {
 const [count, setCount] = useState(0);
 const [initNumber, setInitNumber] = useState(() => 0);
  
  useEffect(() => {
   console.log('count value', count); // 0
   console.log('initNumber value, initNumber); // 0 
  })
    
  return (
   <div>
     <div>Count: {count}</div>
     <div>Init Number: {initNumber}</div>
   </div>
  )
}

Note: If you pass a function as the initial value then react call it internally as you can see in code.

function mountState(initialState) {
  var hook = mountWorkInProgressHook();

  if (typeof initialState === 'function') { // this is the line of code what we are looking 
    initialState = initialState();
  }

  hook.memoizedState = hook.baseState = initialState;
  var queue = hook.queue = {
    last: null,
    dispatch: null,
    lastRenderedReducer: basicStateReducer,
    lastRenderedState: initialState
  };
  var dispatch = queue.dispatch = dispatchAction.bind(null, currentlyRenderingFiber$1, queue);
  return [hook.memoizedState, dispatch];
}

Now let’s see how to update the values.

import React, { useEffect, useState } from 'react';

const HelloComponent = (props) => {
    const [count, setCount] = useState(0);
    return (
        <div>
            <button onClick={() => setCount((oldValue) => {
                const value = oldValue - 1;
                return value;
            })}>Decrement</button>
            <span>{count}</span>
            <button onClick={() => setCount(count + 1)}>Increment</button>
        </div>
    )
}

export default HelloComponent

As you can see in the code we updated the value in two ways. The first one is pretty much clear but the second one we have used whenever we have some dependency on the old value.

useEffect

useEffect is the second most used hook in React. It just called the passed function just after the render is committed to the screen.

Let’s see what I mean by this line.

import React, { useEffect, useState } from 'react';

const HelloComponent = (props) => {
    console.log('Render Start');

    const [count, setCount] = useState(() => {
        console.log('init count state');
        return 0;
    });

    useEffect(() => {
        console.log('Component updated');
    })

    const Component = <div>Hello {count}</div>

    console.log('Render End');
    
    return Component
}

export default HelloComponent

Output:

So you can see on the console ‘Component update’ print just after the “Render End” — (“just after the render is committed to the screen”).

When and how to use it?

When

It has lots of use cases but let me mention the most common one.

  1. use it as the initial first render of the component (ComponentDidMount).
  2. use it when a component goes out of scope (ComponentWillUnMount)
  3. to call or handle any piece of code for a particular state change.

You can learn about the React life-cycle here.

How

import React, { useEffect, useState } from 'react';

const HelloComponent = (props) => {
    const [count, setCount] = useState(0);

    useEffect(() => {
        console.log('call every time when component render/ re-render ');
    })
    
    useEffect(() => {
        console.log('Perfomr action');
    }, []) // ComponentDidMount

    useEffect(() => {
        console.log('call only when component render first time ');
        () => console.log('Cleaning Component') // ComponentWillUnmount
    }, []) // pass empty array as second arguement

    useEffect(() => {
        console.log('call only when component render first time or count get updated ');
    }, [count]) // pass depedent states/ props

    return <div>Hello {count}</div>
}

export default HelloComponent

Please give your attention to the console.log and comments I mention in the code.

For the full article, you can visit https://javascript.plainenglish.io/fundamentals-of-react-hooks-in-6-minutes-by-bytecode-pandit-656e5a38f57

Thanks for reading this article. I hope you enjoyed it.

LEAVE A REPLY

Please enter your comment!
Please enter your name here