New toys, react v16.7.0-Alpha hooks

Source: Internet
Author: User

On Friday, I saw react v16.7.0-Alpha hooks. This morning, I saw hooks in the circle. It was just over the weekend that the IG and G2 games had not started yet...

When I first came into contact with react, I like to use functional components very much, because it is too concise to write very quickly, and then .. After writing it, you will find that many components you have previously written need to be modified .. Why? Because I was not considerate in writing at the time, I found that in the later stage, many places require the lifecycle and status for rendering optimization, and then a lot of changes to the function type as classcomponent. Therefore, classcomponent is usually used in the beginning. Only simple components, such as list items, use functional methods.

Now with hooks, "hooks" means "Hook. In react, Hooks is a series of special functions that enable the function component (functional component) to "Hook" The State and life-cycles inside the react.

?? Rules of hooks
  • Hooks can only be called at the top layer. Do not call hooks in loops, conditions, or nested Functions
  • It can only be used in functional component
?? State hook
  • That is, using state in the function expression
import { useState } from ‘react‘;function Example() {  const [count, setCount] = useState(0);  //const [age, setAge] = useState(42);  //const [fruit, setFruit] = useState(‘banana‘);  //const [todos, setTodos] = useState([{ text: ‘Learn Hooks‘ }]);  return (    <div>      <p>You clicked {count} times</p>      <button onClick={() => setCount(count + 1)}>        Click me      </button>    </div>  );}
  • useStateIs the initial value of the previous state.
  • useStateThe first parameter in the returned value is the previous state, and the second parameter is setstate. However, we only have one State in the past, and now we can name it freely, which is more intuitive, such as the precedingageAndsetAge,fruitAndsetFruit
?? Effect hook
  • Effect hook allows us to use the lifecycle
function FriendStatusWithCounter(props) {  const [count, setCount] = useState(0);  useEffect(() => {    document.title = `You clicked ${count} times`;  });  const [isOnline, setIsOnline] = useState(null);  useEffect(() => {    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);    return () => {      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);    };  });  function handleStatusChange(status) {    setIsOnline(status.isOnline);  }  // ...
  • Useeffect is triggered every time a react is updated (triggered after the first render and each update ).
?? Custom hooks
  • Sometimes, we want to reuse some stateful logic between components.
  • First, we write this logic to usefriendstatus: return the online status of a friend.isOnline
import { useState, useEffect } from ‘react‘;function useFriendStatus(friendID) {  const [isOnline, setIsOnline] = useState(null);  function handleStatusChange(status) {    setIsOnline(status.isOnline);  }  useEffect(() => {    ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);    return () => {      ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);    };  });  return isOnline;}
  • Then we use
function FriendListItem(props) {  const isOnline = useFriendStatus(props.friend.id);  return (    <li style={{ color: isOnline ? ‘green‘ : ‘black‘ }}>      {props.friend.name}    </li>  );}
?? Other hooks
  • You may find some built-in hooks that are not commonly used very useful.
  • Usecontext:
function Example() {  const locale = useContext(LocaleContext);  const theme = useContext(ThemeContext);  // ...}
  • Usereducer
function Todos() {  const [todos, dispatch] = useReducer(todosReducer);  // ...
Summary

You can write functional component more happily in the future ??????

Reference

Overview of react official hooks
Hooks example

Prediction

Wait for the IG to win at. Why is it 3? I want to watch more games.

Last

Hello everyone, here is "taoland". This blog is mainly used to record the growth path of a cainiao programmer. This is the first time I have made a blog. I hope I can communicate with you and grow together! The article will be updated synchronously at the following addresses ......
Personal blog: www.yangyuetao.cn
Applet: taoland

New toys, react v16.7.0-Alpha hooks

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.