Home > Blockchain >  React: Stop Re-render of a section on the change of state
React: Stop Re-render of a section on the change of state

Time:10-27

Bit confused about the concept with the hooks, I have a component where I have two state variables defined with useState:

Now every time one variable changes, it makes the other variable part in JSX to re-render, since it is a list I want to avoid that to be re-rendered. How can I achieve this?

So, in the example below, whenever, I click on the button, it re-renders the list. How can I stop this

import "./styles.css";
import { Fragment, useCallback, useEffect, useState } from "react";
const App = () => {
  const [repos, setRepos] = useState([]);
  const [count, setCount] = useState(1);
  useEffect(() => {
    const fetchRepos = async () => {
      const response = await fetch("https://api.github.com/repositories");
      const repoDetails = await response.json();
      console.log(repoDetails);
      setRepos([...repoDetails]);
    };
    fetchRepos();
  }, []);
  const handleCount = () => {
    setCount(count   1);
  };
  return (
    <Fragment>
      <div className="App">
        {repos.map((r) => {
          console.log("render");
          return <li key={r.id}>{r.name}</li>;
        })}
      </div>
      <button onClick={handleCount}>Button {count}</button>
    </Fragment>
  );
};
export default App;

CodePudding user response:

You can abstract div component containing list items into a separate component and wrap it using React.memo. Pass repos state as prop to it. So that it will only re-render when repos is changed. In case if count changes, it will return memorized version of the list.

CodePudding user response:

Decouple the list tag into a component and memoize it, so that each time the props are same React would simply skip the re-rendering on state change.

React Memoization: https://dev.to/alexgurr/what-is-function-memoization-and-why-should-you-care-5a1l

Demo: https://codesandbox.io/s/keen-glade-fmh6q

  • Related