What is React Hook?
React Hooks are a new addition in react 16.8. Hooks are features that allow you to "hook into" react state and lifecycles into functional components. It lets you use and update the state without using the class component.
Goal of this blog
We will quickly but in-depth see the different hooks and their purposes with code examples so that hooks become super easy to understand and implement in real projects.
Advantages of Hooks
Lets see by an example -
As we all know there are two ways to write react components, one is by the class component and other using the functional component.
A component without a hook: Class component
import React, {Component} from "react";
class Greeting extends Component{
state={
text:"",
};
handleChange = (e) => {
this.setState({ text: e.target.value });
};
render(){
return <input
value={this.state.text}
onChange={this.handleChange}
/>;
}
}
export default Greetings
A component with a hook: Functional Component
import React, {useState} from "react";
const Greeting = () => {
const [text,setText] = useState("");
const handleChange = (e) =>{
setText(e.target.value)
}
return <input
value={text}
onChange={handleChange}
/>;
}
In the first and second scenarios, we are doing the same thing of updating the state but with different components and we can clearly see the second example code is more readable and easy to understand. Also if the codebase increases, class component code can become more complex to read and understand.
classes can confuse both people and machines
So let's understand some most important react hooks with an example -
useState()
useState hook allows you to have state variables in functional components as we had already above. It takes two things an initial state and a setter function to set the state and return the state with the current value.
Let's quickly see an example
import React, {useState} from "react";
const Greeting = () => {
const [text,setText] = useState("");
const handleChange = (e) =>{
setText(e.target.value)
}
return (
<>
<input value={text} onChange={handleChange} />
<div>{text}</div>
</>
)
}
Here function handleChange
is being invoked on every onChange
event and then we are updating the current state of text
using e.target.value, and we can clearly see the updated state in the view.
useEffect()
This hook is designed for managing side effects in the functional components. We basically use this to tell react to do something after the render is done so the name
side effect`
Use-case can be fetching data from the network, directly updating DOM.
It takes two arguments, a function, and a dependency array.
import React, {useState,useEffect} from "react";
const Greeting = () => {
const [text,setText] = useState("");
const handleChange = (e) =>{
setText(e.target.value)
}
useEffect(() => {
document.title = "My React App"
},[])
return (
<>
<input value={text} onChange={handleChange} />
<div>{text}</div>
</>
)
}
Here we are trying to update the title after the react component is rendered. Notice useEffect took two things the first one is callback function and second one is dependency array []
with no element in it. It means the side effect will only run once. We can pass states as a dependency here so that if the state will change then useEffect will re-run.
Like if we want to re-run the useEffect on change of text
state every time we will simply pass that in dependency array. Something like this
useEffect(() => {
document.title = "My React App"
},[text])
And this will update the title everytime we update or change the text state.
useRef()
If we want to persist value between re-renders or if we want some state that don't cause re-render the best choice will be useRef. It can be used to store a mutable value that does not cause a re-render when updated. Also we can directly update the DOM element with useRef.
Let's see an example -
import {useRef} from "react"
export default function App() {
const countRef = useRef(0);
console.log(countRef)
return (
<div className="App">
</div>
);
}
This will console an object having a property current that currently represents the initial value so countRef
is an object. This is a mutable value and we can update or change it anytime we want.
In react every element has a special attribute ref
by which we can also select the DOM elements.
import {useRef} from "react"
export default function App() {
const currentRef = useRef();
console.log(currentRef.current)
return (
<div className="App">
<h2 ref={currentRef}> Hello Hooks </h2>
</div>
);
}
// <h2> Hello Hooks </h2>
So we are able to select the HTMLHeadingElement right? What does it means? Yep, you guessed correctly, we can directly update the DOM element.
import "./styles.css";
import {useRef} from "react"
export default function App() {
const currentRef = useRef();
console.log(currentRef.current)
const clickHandler = () =>{
currentRef.current.style.color = "blue"
}
return (
<div className="App">
<h2 ref={currentRef}>Hello Hooks </h2>
<button onClick={clickHandler}>Fill color</button>
</div>
);
}
here we are directly changing the color as we used to do in vanilla JS. Awesome!!
Summary
- Hooks are features that allow you to "hook into" react state and lifecycles into functional components.
- Using Hooks with functional component is much cleaner and easier to understand to both people and machines
- useState hook allows you to have state variables in functional components.
- It takes an initial state and a setter function and returns the state with the current value.
- useEffect hook is designed for managing `side effects in the functional components.
- Use-case:- fetching data from the network, directly updating DOM.
- takes two arguments, a function, and a dependency array.
- If you want some states that don't cause re-renders to go for useRef, it can directly update DOM.
- useRef is an object having a property current which is mutable
Hope you enjoyed reading about hooks basics. Thanks for staying up to here with me. See you in the next blog ๐๐. I will come back with part two where I will try to cover useContext
and useReducer
Hook. See you soon! Until that