react memo hooks code example

Example 1: useRef

/*
	A common use case is to access a child imperatively: 
*/

function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}

Example 2: react memo

function MyComponent(props) {
  /* render using props */
}
function areEqual(prevProps, nextProps) {
  /*
  return true if passing nextProps to render would return
  the same result as passing prevProps to render,
  otherwise return false
  */
}
export default React.memo(MyComponent, areEqual);

Example 3: how to use react memo hooks

function moviePropsAreEqual(prevMovie, nextMovie) {
  return prevMovie.title === nextMovie.title
    && prevMovie.releaseDate === nextMovie.releaseDate;
}

const MemoizedMovie2 = React.memo(Movie, moviePropsAreEqual);

Example 4: how to use react memo hooks

const computeLetterCount = word => {
    let i = 0;
    while (i < 1000000000) i++;
    return word.length;
  };

  // Memoize computeLetterCount so it uses cached return value if input array ...
  // ... values are the same as last time the function was run.
  const letterCount = useMemo(() => computeLetterCount(word), [word]);

Example 5: react reducer hooks

import React from "react";

// initial state
const initialState = {counter: 0};

// action type
const INC = 'INCREMENT';
const DEC = 'DECREMENT';

// action creator inc
function incActionCreator() {
   return  {
       type: INC,
   }
}

// action creator dec
function decActionCreator() {
   return  {
       type: DEC,
   }
}

// action reducer
function hooksReducer(state, action) {
   switch(action.type) {
   case 'INCREMENT':
      return {
         ...state,
         counter: state.counter++
      }
      case 'DECREMENT':
         return {
            ...state,
            counter: state.counter--
         }
   default:
      return state;
   }
}

// app component
function App () {

  // useReducer is very similar to the store in Redux
  const [stateAction, setDispatchAction] = React.useReducer(hooksReducer, initialState);

  const incClick = (e) =>  setDispatchAction(incActionCreator())
  const decClick = (e) => setDispatchAction(decActionCreator())

  return (
    <>
      <button onClick={incClick}>Incerement</button>
      <button onClick={decClick}>Decrement</button>
      <h4>Counter: {stateAction.counter}</h4>
    </>
  );
}

export default App;