0

How can I make a Hook state change to re-render only the render of the Hook and not the component? I went around this by adding logic to the null returning middleware component, but I don't know if it's a good idea.

import { useState, useMemo, useEffect } from "react";
import "./styles.css";

function useTime() {
  const [a, setA] = useState(0);

  console.log("good-render", a);

  useEffect(() => {
    setInterval(() => {
      setA(a + 1);
    }, 3000);
  }, []);
}

function Aaa() {
  useTime();

  return <></>;
}

export default function App() {
  console.log("bad-render");

  return (
    <div className="App">
      <Aaa />
    </div>
  );
}
2
  • 1
    Please see the How to Ask page--please include the relevant code in the question :) Commented Apr 20, 2021 at 17:17
  • 1
    I rarely ask a question. Done ;) Commented Apr 20, 2021 at 19:03

1 Answer 1

1

Insofar as I'm aware, you can't stop a component rendering from a hook. Whenever the state in a component changes, the component gets set to re-render, which calls all hooks in it. In fact, conditionally calling hooks would break the rules of hooks.

Your best bet would be to encapsulate all the logic you need in refs and effects if you don't want the custom hook to cause a re-render. That being said, unless you have other issues with your code (i.e. a lot of really complicated and time consuming code), then a few extra re-renders isn't the worst thing in the world.

There's definitely a point to the idea that premature optimization is a problem.

That being said, different approaches for preventing the entire tree from re-rendering would be:

  1. Encapsulate the logic in a separate component without children (as you show above)
  2. Use React.memo on the components that make up the children so React can know it should check for changes by reference on all the props to determine whether to re-render.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.