umma.dev

React Hooks

React hooks code snippets.

useState

const Example = () => {
  const [number, setNumber] = useState(0);

  const updateNumber = () => {
    setNumber(number + 1);
  };
  return <button onClick={updateNumber}>click here</button>;
};

useEffect

const Example = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    getData();
  }, []);

  const getData = () => {
    axios
      .get("url")
      .then((res) => setData(res.data))
      .catch((err) => console.log(err));
  };

  return (
    <>
      {data?.map((example) => (
        <p>{example}</p>
      ))}
    </>
  );
};

useMemo

const expensiveFunction = (inputVal) => {
  let expensiveVal = inputVal * 100;
  expensiveVal = "word";
  return expensiveVal;
};

const Example = () => {
  const [input, setInput] = useState("");

  const expensiveVal = useMemo(() => expensiveFuction(input), [input]);

  return <p>The value is {expensiveVal}</p>;
};

useCallback

const Example = () => {
  const [example, setExample] = useState(false)
  const [call] = useState(false)

  const onClick = () => {
    setExample(!state)
  }

  const handler = useCallback(
    (e) => {
      console.log(e.currentTarget)
    },
    [call]
  )
  return (
    <button onClick={onClick}> Click to see parent component state change</button>

    <MyList handler={handler}>
  )
}

Reminder: useCallback shouldn’t be used on onClick

useContext

const UserContext = createContext()

const ComponentOne = () => {
  const [user, setUser] = useState("Person One")

  return (
    <UserContenxt.Provider value= {user}>
      <h1>{`Hello ${user}`}</h1>
      <ComponentTwo />
    </UserContext.Provider>
  )
}

const ComponentTwo = () => {
  return(
    <div>
      Component Two
      <ComponentThree />
    </div>
  )
}

const ComponentThree = () => {
  return (
    <div>
      Component Three
      <ComponentFour />
    </div>
  )
}

const ComponentFour = () => {
  const user = useContext(UserContext)

  return (
    <div>
      Component Four
      <p>{`Hello ${user} again`}</p>
    </div>
  )
}

useRef

const Example = () => {
  let ref = useRef(0);

  const onClick = () => {
    ref.current = ref.current + 1;
    alert("You clicked " + ref.current + " times.");
  };

  return <button>Click here!</button>;
};

useReducer

const reducer = (state, action) => {
  if(action.type === 'incremented_age') {
    return {
      age: state.age + 1
    }
  }
}

const Example = () => {
  const [state, dispatch] = useReducer(reducer, { age: 42 })

  return (
    <div>
      <button onClick{() => {
        dispatch({type: 'incremented_age})
      }}>
        Increment age
      </button>
      <p>You are {state.age} years old.</p>
    </div>
  )
}