Search code examples
reactjsreact-hooksuse-effect

ReactJS: How to detect value changed into another componet and compare with previous?


I am doing a simple exercise to clear my hook concept.

In my current scenario, I need to call the API only if i click on the Call API button and that time the page number should be the current value of Click Me button value.

But currently, on every Click Me button click the API is called.

I have tried with this solution, but can not get the result.

const usePrevious = (value) => {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  console.log(ref.current);
  return ref.current;
};

export default function GetAPIData(props) {
  const [chars, setChars] = useState([]);
  const prevCount = usePrevious(props.id);
  console.log(
    "Previous value is: " + prevCount,
    "Current value is: " + props.id
  );

  useEffect(() => {
    axios
      .get(`https://rickandmortyapi.com/api/character/?page=${props.id}`)
      .then((res) => {
        setChars(res.data.results);
      })
      .catch((err) => {
        alert(err.message);
      });
  }, [prevCount, props.id]);

  return (
    <div className="container">
      <h3>
        <span>Achtung,</span> ein Trend geht um
      </h3>
    </div>
  );
}

Here is the working Sandbox URL for reference.


Solution

  • You are updating the state every time when you click on the button by that the page was re-render and useEffect() is calling the API. Try to create a new state which only changes when you click on the Call API. By that, your component does not re-render on the change of count. Might it help You