React hooks

Run the following to create a workspace for your components:

$bit
Copiedcopy
See command synopsis

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.

Create a component

Run the following to create a React component using your env's react-hook template:

$bit
Copiedcopy
See command synopsis
Component compilation

Run Bit's development server (bit start) or watch mode (bit watch) to compile modified components.

Implementation file

/* @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 };
}
CopiedCopy

Main file

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';
CopiedCopy

Tests

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);
});
CopiedCopy

Use the hook in a React component

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>
  );
}
CopiedCopy