skip to Main Content

Test and Test2 component import useState value test from custom hook(useTest.ts).
I thought both components will be re-rendered when I click "clicked me" because imported useState value test will be updated.
But actually, only Test component is re-rendered. Can anyone explain the reason for me …?

App.tsx

import React from 'react';
import { Test } from './Test';
import { Test2 } from './Test2';

function App() {
  return (
    <>
      <Test />
      <Test2 />
    </>
  );
}

export default App;

Test.tsx

import { useTest } from "./hooks/useTest";

export const Test = () => {
  console.log("Test1 is rendered");

  const {test, testSet, increment} = useTest();

  return (
    <div>
      <h1>Test1</h1>
      <h2>{test}</h2>
      <h2>{testSet}</h2>
      <button onClick={() => {increment()}}>Click me</button>
    </div>
  );
}

Test2.tsx

import { useTest } from "./hooks/useTest";

export const Test2 = () => {
  console.log("Test2 is rendered");
  const {test, testSet} = useTest();

  return (
    <div>
      <h1>Test2</h1>
      <h2>{test}</h2>
    </div>
  );
}

useTest.ts

import { useState } from "react";

export const useTest = () => {
  const [test, setTest] = useState(["orange", "apple", "banana"]);
  const [count, setCount] = useState(0);
  const testSet = new Set(test);

  const increment = () => {
    setCount(count+1)
    setTest(pre => [...pre, `grape${count}`])
    // setTest(newTest);
  };

  return { test, testSet, increment}

}

3

Answers


  1. Each component has its own state. The useTest hook creates state in each component that uses it; there’s no connection between those states.

    If you want to share state between components, you need to move the state into their parent component, and then pass it down as properties.

    Login or Signup to reply.
  2. The reason only Test is re-rendered is due to the specific state dependencies each component has. Test depends on testSet, which changes on each render, triggering a re-render. Test2 only depends on test, which doesn’t change in a way that requires Test2 to re-render.

    Login or Signup to reply.
  3. Hooks are used to share the stateful logic between multiple components. There is a great explanation on the react docs.

    Custom Hooks let you share stateful logic but not state itself. Each call to a Hook is completely independent from every other call to the same Hook.

    If you want your components to be re-rendered when the state value changes, you can use the context api

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search