Hooks is a feature you’ll use every day of your React development. React hooks are available in React version 16.8. Hooks are great because we get more tools from React developers.
1. What are hooks?
React hooks are a way to add React.Component functionality to functional components: state and lifecycle. Hooks let you use the functionality of react without a class.
2. React’s state hook
For example, we have 1 state in the component:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import React, { Component } from 'react'; class JustAnotherCounter extends Component { state = { count: 0 }; setCount = () => { this.setState({ count: this.state.count + 1 }); }; render() { return ( <div> <h1>{this.state.count}</h1> <button onClick={this.setCount}>Count Up To The Moon</button> </div> ); } } |
With Hooks we can write more briefly as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 | import React, { useState } from 'react'; function JustAnotherCounter() { const [count, setCount] = useState(0); return ( <div> <h1>{count}</h1> <button onClick={() => setCount(count + 1)}>Count Up To The Moon</button> </div> ); } |
Note that the functional component will be much easier for React newbies.
3. useState ()
You may not be familiar with the useState () syntax, which uses destructuring assignment for arrays. This is almost the same as the way we pull props out of an object with the destructuting object. Compare object destructuring and array destructuring to see why array usage is more effective. Object destructuring requires more writing to retrieve a variable and rename it.
- Object Destructuring:
1 2 3 4 5 6 | // object destructuring. lots of writing! const users = { admin: 'chris', user: 'nick' }; // grab the admin and user but rename them to SuperAdmin and SuperUser const { admin: SuperAdmin, user: SuperUser } = users; |
The above lines can be a little difficult to read, but with array destrcuturing we just need to name the variable as we take it out of the array. The first variable is the first item of the array.
- Array Destructuring:
1 2 3 4 5 6 | // array destructuring const users = ['chris', 'nick']; // grab in order and rename at the same time const [SuperAdmin, SuperUser] = users; |
Short and easy to understand, isn’t it.
- What does useState () give us?
useState () provides 2 variables and we can name those 2 variables as we like. Just be satisfied: the first variable is value, just like this.state, the second is a function to update that value, like this.setState. The last part passed to useState is the argument we passed to it. The argument of useState () is the initial value of the state. In the above example, the initial value of the variable count is 0.
- What is bad about classes?
The introduction to React hooks provides a nice thing: Classes confuse both people and machines This means that classes can sometimes be confusing and can be written in any way. Dive into someone else’s project and you can enter a world of different syntax and style options. There are no plans to remove support classes. We have another way to code. By allowing classes to be converted into functional components, we can even break down parts of the application into smaller and more focused components.
- Using multiple state hooks: We can use useState multiple times in the same function:
1 2 3 4 5 6 7 8 9 10 | import React, { useState } from 'react'; function AllTheThings() { const [count, setCount] = useState(0); const [products, setProducts] = useState([{ name: 'Surfboard', price: 100 }]); const [coupon, setCoupon] = useState(null); return <div>{/_ use all those things here _/}</div>; } |
3. Effect Hook
State hooks allow us to use state in React functional components. This takes us one step closer to using functional components on class components. The next part of the transition to functional components is the lifecycle method.
The effect is similar to the componentDidMount, componentDiaUpdate, componentWillUnmount components.
This is what the Effect hook works for. Side-effects are what you want your app to do:
- fetching data
- DOM changes
- set up registration
The effect will run after each render, including the first render. Let’s compare class vs functional component:
1 2 3 4 5 6 7 8 9 10 11 12 13 | import React, { Component } from 'react'; class DoSomethingCrazy extends Component { componentDidMount() { console.log('i have arrived at the party!'); document.title = 'preesent'; } render() { return <div>stuff goes here</div>; } } |
1 2 3 4 5 6 7 8 9 | function DoSomethingCrazy() { useEffect(() => { console.log('i have arrived at the party!'); document.title = 'preesent'; }); return <div>stuff goes here</div>; } |
Only run the Effect hook when something changes: Since useEffect () runs every time a component is rendered, how does it only work once? The effect hook can take a second argument as an array. It will look through the array and only run the effect if one of those values changes. For example :
- (componentDidMount): only runs once
1 2 3 4 5 | // only run on mount. pass an empty array useEffect(() => { // only runs once }, []); |
- componentDidUpdate: runs when there is a change
1 2 3 4 5 6 7 8 | // only run if count changes useEffect( () => { // run here if count changes }, [count] ); |
- What about componentWillUnmount: To run something before the component unmounts, we just need to return a function in useEffect ():
1 2 3 4 5 6 7 8 9 | useEffect(() => { UsersAPI.subscribeToUserLikes(); // unsubscribe return () => { UsersAPI.unsubscribeFromUserLikes(); }; }); |
4. Combine useEffect and state
No problem if combined using them. Together they can create functional components that act as component classes. This is a practical example of a component fetching a user list from the Github API with useEffect () and useState (). We will start by using useState () for users:
1 2 3 4 5 6 | import React, { useState } from 'react'; function GitHubUsers() { const [users, setUsers] = useState([]); } |
We set users as an empty array into useState([])
. Next we put in useEffect () and use fetch to get data from the API:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import React, { useState } from 'react'; function GitHubUsers() { const [users, setUsers] = useState([]); useEffect(() => { fetch('https://api.github.com/users') .then(response => response.json()) .then(data => { setUsers(data); // set users in state }); }, []); // empty array because we only run once } |
Note that we are setting the second argument of useEffect to be an empty array so it only runs once. Finally, we will display that list
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import React, { useState, useEffect } from 'react'; import ReactDOM from 'react-dom'; function GitHubUsers() { // ...other stuff here... return ( <div className="section"> {users.map(user => ( <div key={user.id} className="card"> <h5>{user.login}</h5> </div> ))} </div> ); } |
Conclude
Reat state and Effect hook are great and will be a tool to help React learn easier for newbie. A lot of Vue’s success is in its simplicity of component creation. It is just an object. Now with React. You don’t need to distinguish between “is it a class” or “should I use a functional component”?
Source: https://scotch.io/tutorials/getting-started-with-react-hooks#toc-what-is-this-usestate-syntax-