ReactJS Hooks
Hooks
Hooks were added and introduced in React 16.8. We can use state and other React features without composing a class. Hooks enable us to make use of these features in functional ReactJS components. Hooks allow us to attach ReactJS state and lifecycle features from function components and we can use more React’s features without using classes.
We need to understand a few things about hooks before moving ahead,
- Hooks are optional. If you don’t want to learn or use Hooks you can skip them.
- Hooks are fully backward-compatible. Hooks don’t hold any breaking changes.
- They are not there to remove classes from React.
- You do not need to update or replace your existing knowledge about React concepts.
- You can gradually adopt hooks in your programming practice.
To understand hooks, let us take a simple component that generates a random integer number between 0 to 9 on every button click.
class RandomComp extends React.Component { constructor() { super(); this.state={ rand:0 }; this.updateNumber=this.updateNumber.bind(this); } updateNumber() { const num=Math.floor(Math.random() * 10); this.setState({rand:num}); } render() { return <div><button onClick={this.updateNumber}> Random</button> <br/> <h3>{this.state.rand}</h3> </div>; } } ReactDOM.render(<RandomComp/>,document.getElementById('root'));
Conventionally, this can not be done using a functional component, but we can create a component using a function with a state hook.
The same component can be written using the state hook as,
function RandomComp() { const [number, getRandom] = useState(0); var num=()=>Math.floor(Math.random() * 10); return (<div> <h1>{number}</h1> <button onClick={() => getRandom(num)}>Random</button> </div> ); } ReactDOM.render(<RandomComp />,document.getElementById('root'));
The useState() method uses a destructuring assignment for arrays.
const [number, getRandom] = useState(0);
- The first variable is the state value
- The second variable is a function to update the state value
- The useState methods argument is the initial state value
Another example,
function RandomComp(props) { const imagearr=props.images; const len=imagearr.length; const [current, getNum] = useState(0);//Hook return (<div> <button onClick={() => getNum(Math.abs((current-1)%len))}>Prev</button> <img src={imagearr[current]} alt='unable to load'/> <button onClick={() => getNum(Math.abs((current+1)%len))}>Next</button> </div> ); } //Image url array const srcs=[ 'https://image.shutterstock.com/image-photo/selective-focus-clay-teapot-white-260nw-1512218261.jpg', 'https://image.shutterstock.com/image-photo/blue-flowers-orchids-orchidaceae-260nw-1088929511.jpg', 'https://image.shutterstock.com/image-photo/streaked-orchid-flowers-beautiful-260nw-299701991.jpg', 'https://image.shutterstock.com/image-photo/orchids-260nw-142122841.jpg', 'https://image.shutterstock.com/image-photo/grammatophyllum-speciosum-giant-orchid-tiger-260nw-1646571589.jpg']; ReactDOM.render(<RandomComp images={srcs} />,document.getElementById('root'));
the result will appear as,
Multiple state hooks
Multiple state hooks can be used in the same way. For example,
import React, { useState } from 'react'; function AllTheThings() { const [count, setCount] = useState(0); const [volume, setSize] = useState(null); const [item, setItem] = useState([{ itemName: 'Cynlinder', ht: 100 , wd : 44}]); return <div>{/_ use all those things here _/}</div>; }
The Effect hook
For example, a Timer component can be created, that will be updated after each second to display current time and date.
function Timer(props) { const t=new Date().toLocaleString(); const[time, setTime]=useState(t); useEffect(() => { setInterval(() => { setTime(() => new Date().toLocaleString() ); }, 1000); }); return <div><h2>{time}</h2></div>; } ReactDOM.render(<Timer />,document.getElementById('root'));
The useEffect() method will transmit the effects in the time variable after each second and the time will be updated on the screen.