Skip to main content

3 posts tagged with "react-hooks"

View All Tags

· 2 min read
Gavin Gong

在React(typescript)中渲染需即时加载的元素。主要思路是使用useEffect Hook加载内容,而后使用useState Hook在加载完成时重新渲染界面。简短的代码描述如下:

interface AsyncCompomentProps {
func: () => Promise<JSX.Element>;
default?: JSX.Element;

function AsyncComponent(props: AsyncCompomentProps) {
const [loaded, setLoaded] = useState<JSX.Element>(null);
useEffect(() => {
props.func().then((result) => {
}, []);
return loaded ? loaded : props.default ?? <div>Loading...</div>;

func={async () => {
await new Promise((r) => setTimeout(r, 3000));
return <div>hi</div>;
default={<div>I'm loading...</div>}

· 4 min read
Gavin Gong

Hooks are a new addition in React 16.8. They let you "hook into" React state and lifecycle features from function components. Hooks don't work inside classes — they let you use React without classes. In older React, it's hard to reuse stateful logic between components. The older React doesn't offer a way to "attach" reusable behavior to a component. With Hooks, you can extract stateful logic from a component so it can be tested independently and reused. Hooks allow you to reuse stateful logic without changing your component hierarchy. This makes it easy to share Hooks among many components or with the community.

There are nine of them: