Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: If I import a useState value from hook, will the component be re-rendered?

Tags:

reactjs

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}

}
like image 335
Nanano Avatar asked Dec 28 '25 06:12

Nanano


2 Answers

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.

like image 103
ruakh Avatar answered Dec 30 '25 21:12

ruakh


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

like image 30
emkarachchi Avatar answered Dec 30 '25 22:12

emkarachchi