Skip to content

Instantly share code, notes, and snippets.

@MarshalW
Last active May 17, 2022 08:01
Show Gist options
  • Save MarshalW/25a402baad1e75eba213274697cdf72f to your computer and use it in GitHub Desktop.
Save MarshalW/25a402baad1e75eba213274697cdf72f to your computer and use it in GitHub Desktop.
react hooks examples

react hooks examples

import "./styles.css";

import {
  useState,
  useEffect,
  createContext,
  useContext,
  useReducer
} from "react";

// useReducer
const initialState = {
  count: 0,
  time: new Date().toLocaleTimeString()
};

function reducer(state, action) {
  switch (action.type) {
    case "add":
      return {
        count: state.count + 1,
        time: new Date().toLocaleTimeString()
      };
    default:
      throw new Error();
  }
}

function ReducerActionButton() {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <button
      onClick={() => {
        dispatch({ type: "add" });
      }}
    >
      useReducer, {state.count}, {state.time}
    </button>
  );
}

// useContext
const MyContext = createContext("default");

// useReducer

// hooks customer
function useOnlineStatus() {
  let [online, setOnline] = useState(false);
  setTimeout(() => {
    setOnline(true);
  }, 1000 * 3);

  return online;
}

// useEffect
const Clock = () => {
  let [time, setTime] = useState(new Date().toLocaleTimeString());
  useEffect(() => {
    let timerId = setInterval(() => {
      setTime(new Date().toLocaleTimeString());
    }, 1000);

    return () => {
      clearInterval(timerId);
    };
  });
  return (
    <div>
      <p>
        useEffect:
        <span>
          {time}, {useContext(MyContext)}
        </span>
      </p>
    </div>
  );
};

// useState
const ActionButton = () => {
  let [count, setCount] = useState(0);
  let online = useOnlineStatus();

  if (!online) {
    return <div>Loading..</div>;
  }

  return (
    <button
      onClick={() => {
        setCount(count + 1);
      }}
    >
      useState, {count}
    </button>
  );
};

export default function App() {
  return (
    <div className="App">
      <h1>hooks</h1>
      <MyContext.Provider value="button">
        <ActionButton />
      </MyContext.Provider>
      <p></p>
      <ReducerActionButton />
      {/* <MyContext.Provider value="clock"> */}
      <Clock />
      {/* </MyContext.Provider> */}
    </div>
  );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment