ReactJS Foundations

Listing 11-12: Function dependencies cause unnecessary renders

Previous Listing | Next Listing

import {useEffect,useState,useRef} from 'react';

function CallMe(props){

  const [phoneNumber,setPhoneNumber] = useState();
  const [currentNumber,setCurrentNumber] = useState();

  const phoneInputRef = useRef();

  const handleClick = (e)=>{
      setPhoneNumber(currentNumber);
  }

  const placeCall = () => {
    if(currentNumber){
      console.log(`dialing undefined`);
    }
  };
  
  
  useEffect(() => {
    placeCall(phoneNumber);
  },[phoneNumber,placeCall]);

  return(
    <>
      <label>Enter the number to call:</label>
      <input type="phone" ref={phoneInputRef} onChange={()=>{setCurrentNumber(phoneInputRef.current.value)}}/>
      <button onClick={handleClick}>
        Place Call
      </button>
      <h1>{currentNumber}</h1>
    </>
  );
}

export default CallMe;

Download the examples, report issues, and ask/answer questions in the discussion area by visiting the book's github page. All of the code for the book is also available on codesandbox.io for you to play around with.

ReactJS Foundations is published by John Wiley and Sons, Inc and is available in paperback and eBook.

React JS Foundations

Loading...