OR
let _index = 0;Вот вывод консоли:
const useIndex = () => {
const index = useMemo(() => _index++, []);
// const [index] = useState(_index++); - same problem
console.log("INDEX", index);
return index;
};
const useHook = () => {
const index = useIndex();
console.log("Now index is", index);
useEffect(() => {
return () => {
console.log(`Remove ${index}`);
};
}, []);
return { index };
};
export default function App() {
const [isIndex, setIsIndex] = useState(true);
return (
<div className="App">
{isIndex && <NonIndexComponent />}
{!isIndex && <IndexComponent />}
<button onClick={() => setIsIndex(!isIndex)}>
Toggle indexes components
</button>
</div>
);
}
const IndexComponent = () => {
const { index } = useHook();
return <h1>My index is {index}</h1>;
};
const NonIndexComponent = () => {
return <h1>I'm without index</h1>;
};
INDEX 0Почему один компонент получает разные индексы?
Now index is 0
INDEX 1
Now index is 1
// вывод ниже после удаления компонента
Remove 1
Codesandbox - https://codesandbox.io/s/gallant-hooks-1drpy?file=/src/App.js