Monday, 14 October 2019

react hooks useInterval

setInterval with hooks is as egg on React’s face. useInterval() Is a Better API.


blink every second, click toggle to stop or resume

//react native
import React, { useState } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import useInterval from 'react-useinterval';

function Blink(props) {
  const [show, setShow] = useState(true);
  const [delay, setDelay] = useState(1000);

  //useInterval is a custom react hook, use at top level of function
  useInterval(() => (
    setShow(!show)
  ), delay);

  toggleBlink = () => {
    if (delay) {
      setDelay(null)
    }
    else {
      setDelay(1000)
    }
  }

  return (
    <View style={{ flexDirection: 'row', justifyContent: 'space-between', marginVertical: 5 }}>
      <Text>{show ? props.text : 'hide'}</Text>
      <Button title='toggle' onPress={() => toggleBlink()}></Button>
    </View>
  );

}

export default function BlinkApp(){
    return (
      <View style={{ marginTop: 30 }}>
        <Blink text='I love to blink' />
      </View>
    );
  }

reference:
https://overreacted.io/making-setinterval-declarative-with-react-hooks/
https://www.npmjs.com/package/react-useinterval
https://facebook.github.io/react-native/docs/button

3 comments: