In TypeScript, you can pass the useState as a prop to a component. Here’s how you can do it:
{`// ParentComponent.tsx import React, { useState } from 'react'; import ChildComponent from './ChildComponent'; const ParentComponent: React.FC = () => { const [count, setCount] = useState(0); return ( ); }; export default ParentComponent; // ChildComponent.tsx import React from 'react'; interface Props { count: number; setCount: React.Dispatch>; } const ChildComponent: React.FC = ({ count, setCount }) => { const increment = () => { setCount(count + 1); }; const decrement = () => { setCount(count - 1); }; return ( ); }; export default ChildComponent; `}Count: {count}
In this example, the ParentComponent holds the state variable count using the useState hook. It then passes the count and setCount functions as props to the ChildComponent.
The ChildComponent receives these props and uses them to update the count state in the parent component. The count is displayed in a paragraph element and the increment and decrement functions are triggered by buttons.