"Magic" using React Hooks. Yes, you read it right.
Sidhartha Mallick
Posted on February 7, 2022
First things first, What are hooks ?
Hooks are the new feature introduced in the React 16.8 version. It allows you to use state and other React features without writing a class. Hooks are the functions which "hook into" React state and lifecycle features from function components.
When would I use a Hook?
If you write a function component and realize you need to add some state to it, previously you had to convert it to a class. Now you can use a Hook inside the existing function component. We’re going to do that right now!
What all Hooks are there ?
- useState
- useEffect
- useContext
- useRef
- useReducer
- useMemo
- useCallback
- useLayoutEffect
Yes, the name of the hooks always start with
use
Let's learn more about these hooks, later in this blog.
Here is a github repo and webpage demonstrating the usage of all the hooks.
Github Repository : github-link
Demo : demo-link
useState :
const [count, setCount] = useState(0);
It declares a “state variable”. Our variable is called count but we could call it anything else, like banana. This is a way to “preserve” some values between the function calls — useState is a new way to use the exact same capabilities that this.state provides in a class. Normally, variables “disappear” when the function exits but state variables are preserved by React.
import { useState } from 'react';
export default function FunctionUsingUseState(){
const [count, setCount] = useState(0);
return (
<div>
<button onClick={() => setCount(count + 1)}>
Count : {count}
</button>
</div>
);
}
useEffect
It does the work of componentDidMount
as is in React.Component
class. By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed (we'll refer to it as our “effect”), and call it later after performing the DOM updates.
import { useState, useEffect } from 'react';
export default function UseStateUseEffect(){
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Use Effect is called');
}, [count]);
return (
<div>
<button onClick={() => setCount(count + 1)}>
Count : {count}
</button>
</div>
);
}
useContext
This hook is used to create common data that can be accessed throughout the component hierarchy without passing the props down manually to each level.
import { useState, useContext, createContext } from 'react';
const MoodContext = createContext(moods);
export default function FunUseContext(){
const [mood, setMood] = useState('😁');
return (
<MoodContext.Provider value={mood}>
<div>
<button onClick={() => setMood('🤬')}>Angry</button>
<button onClick={() => setMood('😁')}>Happy</button>
<button onClick={() => setMood('😔')}>Sad</button>
<p>I am in <i>Parent</i> Function : {mood}</p>
</div>
<MoodEmoji/>
</MoodContext.Provider>
);
}
function MoodEmoji(){
const mood = useContext(MoodContext);
return (
<div>
<p>I am Inside <i>useContext</i> Function : {mood}</p>
</div>
);
}
useRef
It's a way to create a reference to a value in the component, and use it in the component's lifecycle.
It is Mutable, but, it doesn't re-render UI. It is mainly used to grab DOM Elements.
More common usecase of useRef is to grab native HTML elements from JSX.
import { useRef } from 'react';
export default function FunctionUsingUseRef(){
const myBtn = useRef(null);
const clickIt = () => myBtn.current.click();
const helloButtonClicked = () => console.log('hello button clicked');
return (
<div>
<p>Check the console.</p>
<button ref={myBtn} onClick={helloButtonClicked}>Hello Button</button>
<button onClick={clickIt}>Click Me! When You Click Me, You Indirectly Click 'Hello Button', Isn't that interesting.</button>
</div>
);
}
useReducer
Redux type of functionality, to useReducer to update state in Functional Components in React.
import { useReducer } from 'react';
function reducer(state, action) {
switch(action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}
export default function FunctionUsingUseState(){
const [count, dispatch] = useReducer(reducer, 0);
return (
<div>
<h3>{count}</h3>
<button onClick={() => dispatch({type: 'DECREMENT'})}>-</button>
<button onClick={() => dispatch({type: 'INCREMENT'})}>+</button>
</div>
);
}
useMemo
This hook is a higher-order component that takes a function as an argument and returns a memoized version of that function.
import { useMemo, useState } from 'react';
export default function FunUseMemo(){
const [count, setCount] = useState(60);
// useMemo is a higher-order component that takes a function as an argument
// and returns a memoized version of that function.
const expensiveCount = useMemo(() => {
return count ** 2;
}, [count]);
return (
<div>
<button onClick={() => setCount(count + 1)}>
Count : {count}
</button>
<p>Expensive Count : {expensiveCount}</p>
</div>
);
}
useCallback
In order to Memoize a whole function, useCallback is used.
The showCount function is called from multiple childs in the same DOM Tree, they will help prevent un-necessary re-renders of the same object as they will be using the same function object.
useLayoutEffect
It is similar to useEffect with a small difference.
It runs after render but before it it is visually updated.
It blocks visual updates until the Callback exection is finished.
Reach Out to Me @mallicksidhartha7@gmail.com
Github
LinkedIn
Posted on February 7, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.