react hook example

Example 1: state with react functions

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    

You clicked {count} times

); }

Example 2: hooks in react

import React, { useState, useEffect } from "react";
export default props => {
  console.log("componentWillMount");
  console.log("componentWillReceiveProps", props);
  const [x, setX] = useState(0);
  const [y, setY] = useState(0);
  const [moveCount, setMoveCount] = useState(0);
  const [cross, setCross] = useState(0);
  const mouseMoveHandler = event => {
    setX(event.clientX);
    setY(event.clientY);
  };
  useEffect(() => {
    console.log("componentDidMount");
    document.addEventListener("mousemove", mouseMoveHandler);
    return () => {
      console.log("componentWillUnmount");
      document.removeEventListener("mousemove", mouseMoveHandler);
    };
  }, []); // empty-array means don't watch for any updates
  useEffect(
    () => {
      // if (componentDidUpdate & (x or y changed))
      setMoveCount(moveCount + 1);
    },
    [x, y]
  );
useEffect(() => {
    // if componentDidUpdate or componentDidMount
    if (x === y) {
      setCross(x);
    }
  });
  return (
    

Your mouse is at {x}, {y} position.

Your mouse has moved {moveCount} times

X and Y positions were last equal at {cross}, {cross}

); };

Example 3: react usestate

function Counter({initialCount}) {
  const [count, setCount] = useState(initialCount);
  return (
    <>
      Count: {count}
      
      
      
    
  );
}

Example 4: react hooks

import React, { useState, useEffect } from 'react';
function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:  useEffect(() => {    // Update the document title using the browser API    document.title = `You clicked ${count} times`;  });
  return (
    

You clicked {count} times

); }

Example 5: react hooks

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"  const [count, setCount] = useState(0);
  return (
    

You clicked {count} times

); }

Example 6: React looping hooks to display in other hook

import React, { useState } from "react";

function App() {

  const [list, setList] = useState(" ");

  const [items, updateOnClick] = useState([ ]);

  function updateList(event) {
    const valueEntered = event.target.value;
    setList(valueEntered);
  }

  function updateClick(){
     updateOnClick(list);
     }
 return (
           
            
            
    {items.map(item =>
  • {item}
  • ) }
);} export default App;

Tags: