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}
}
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With