Course contentsShow
← React
Lesson 2100 of 2,39646. Testing React with RTLFree lesson

Passing Initial Props to renderHook

Providing initialProps to test hooks that depend on parameters or configuration.

Passing Initial Props to renderHook

You'll learn how to test hooks that need configuration or parameters by providing initial props to renderHook.

The Problem: Hooks with Parameters

Many hooks accept parameters that configure their behavior. When testing these in isolation, you need a way to simulate passing different props—just like you would when using the hook inside a component. The renderHook function accepts an initialProps option specifically for this scenario.

How It Works

Think of renderHook as creating an invisible wrapper component. Just as you'd pass props to a real component, you can pass initialProps to this wrapper, which then flow into your hook.

const { result, rerender } = renderHook(
  (props) => useCustomHook(props.userId, props.config),
  {
    initialProps: { userId: 123, config: { enabled: true } }
  }
);

The first argument is now a function that receives the props and calls your hook with them. The second argument provides the starting values.

Testing Different Configurations

This pattern shines when testing how hooks respond to different parameters:

test('handles different user IDs', () => {
  const { result } = renderHook(
    ({ id }) => useUser(id),
    { initialProps: { id: 5 } }
  );
  
  expect(result.current.userId).toBe(5);
});

You can also combine this with rerender to test how your hook responds when props change (which you already learned).

Key Takeaway: Use initialProps to pass configuration or parameters into hooks during testing, enabling you to verify behavior across different scenarios without creating wrapper components.