Run the following to create a workspace for your components:
The generated workspace includes workspace-level configuration, configuration files for your IDE, and a customizable React env for your React component development.
To learn how to initialize a Bit workspace on an existing project, see Add Bit to an existing project.
Run the following to create a React component using your env's react-hook template:
Component compilation
Run Bit's development server (bit start
) or watch mode (bit watch
) to compile modified components.
/* @filename: use-counter.tsx */ import { useState } from 'react'; export function useCounter() { const [count, setCount] = useState(0); const increment = () => setCount((c) => c + 1); return { count, increment }; }
Expose your component's API and public types in the component's main file (index.ts
, by default):
/* @filename: index.ts */ export { useCounter } from './welcome.tsx';
Head over to your component's .spec.tsx
file to add automated testing. For example:
/* @filename: use-counter.spec.ts */ import { renderHook, act } from '@testing-library/react-hooks'; import { useCounter } from './use-counter'; it('should increment counter', () => { const { result } = renderHook(() => useCounter()); act(() => { result.current.increment(); }); expect(result.current.count).toBe(1); });
Import the React hook into a React component using its package name (whether it is maintained in the same workspace or installed from a remote scope):
/* @filename: path/to/component/dir/counter.tsx */ /** * import components using their package name * do not use relative paths * */ import { useCounter } from '@learnbit-react/hooks.use-counter'; export function Counter() { const { count, increment } = useCounter(); return ( <div> <button onClick={increment}>+</button> <span>{count}</span> </div> ); }