Before the introduction of Hooks, we could only create and manage State using a class-based component, we couldn't do such with a functional component as it was a stateless component, but with the introduction of Hooks in React 16.8, we can now use state and other React features without a class.
We define a Hook according to the official React documentation as "a special function that lets you 'hook into' React features". So you do not need to rewrite a functional component to a class component before you can add State but you can use a Hook inside the functional component to add State.
Let us look at the first React Hook which is the useState
(Hook State).
To use it you would need to import it
import React, {useState} from 'react'
After importing it, we can now use Hook in this way;
import React, {useState} from 'react'
const App=()=> {
const [count, setCount] = useState(0);
return (
<div>
<h4>You clicked {count} times</h4>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export default App;
You can see from the code above that the value of useState
is the initial value of state when we load our application (0), we then increment state.count
when a user clicks a button by calling the this.setState()
.
Let us create the equivalent of the above application using a class component.
import React from 'react'
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
export default App;
We can see that from both cases we had to read state and then update state.
Things to note when using Hook
- You can only call hook at the top level and not inside of a condition, a loop, or a nested function.
- Hooks can only e called inside of a React component and not inside a regular JavaScript function.
- You can also declare more than one state variable (multiple variables).
Another React Hook we will be looking at is the useEffect
(Hooks Effect) it allows us to perform a side effect (actions) on functional components. The useEffect
does not use life cycle methods (componentDidMount(), componentDidUpdate() and componentWillUnmount() ) that are used in a class component.
The most common feature of useEffect
is in fetching and consuming data from an API and also updating the DOM (Document Object Model).
We will take a look at how we can use useEffect
to fetch data from an API.
We are going to be building a News application that displays the latest news within our region. We are getting our data from newsapi.org
So below is our /App.js
component. We created a state for news, with an empty useState, after fetching data from the API, we set our state to the data we got.
import React, { useEffect, useState } from 'react'
import News from './News'
import './App.css'
const App=()=>{
const [news, setNews] = useState([])
useEffect( () =>{
getNews()
}, [query]);
const getNews = async ()=>{
const response = await fetch(`https://newsapi.org/v2/top-headlines?country=ng&apiKey=YOUR-API-KEY`)
const data = await response.json()
setNews(data.articles)
}
return(
<div className="App">
{news.map(news =>(
<News
key={news.title}
title={news.title}
author={news.source.name}
date={news.publishedAt}
description={news.description}
link={news.url}
photo={news.urlToImage}
/>
))}
</div>
)
}
export default App;
Below is our /News.js
component.
import React from 'react'
const News =({title, author, date, description, link, photo})=>{
return(
<div className="row news">
<div className="col-md-6">
<h3>{title}</h3>
<h6>Source: {author}</h6>
<h6>Publication Date: {date}</h6>
<p>{description} <a href={link}>Read Content</a></p>
</div>
<div className="col-md-6">
<img className="img-fluid justify-content-center" src={photo} alt="..." width="600px"/>
</div>
</div>
)
}
export default News;
We can see from the above that in using the useEffect
to fetch data from an API, we do not use the lifecycle method as used when doing so in a class-based component.
Conclusion
React hook is a great addition to the library and an interesting aspect of React Js as understanding it will help you to include state in functional component, there are other things to understand in Hooks, and will advise that you read through the official documentation for more understanding.
You can get the complete project on everything on this article here.
Thanks for reading!😊
Top comments (0)