DEV Community

Apollo
Apollo

Posted on

How to integrate DeepSeek R1 into your React app

Integrating DeepSeek R1 into Your React App: A Comprehensive Technical Guide

DeepSeek R1 is a powerful AI-based search engine that enables intelligent, context-aware search capabilities. By integrating DeepSeek R1 into your React app, you can enhance user experience with advanced search functionality. This guide will walk you through the process step-by-step, including authentication, API integration, and result rendering in a React component.


Prerequisites

Before proceeding, ensure you have the following:

  1. A DeepSeek R1 API key (obtainable from the DeepSeek developer portal)
  2. Node.js and npm installed
  3. A React project set up (use create-react-app if you're starting from scratch)

Step 1: Install Required Dependencies

To integrate DeepSeek R1, you’ll need to install axios for making HTTP requests and dotenv to manage environment variables securely.

Run the following command in your terminal:

npm install axios dotenv
Enter fullscreen mode Exit fullscreen mode

Step 2: Configure Environment Variables

Store your DeepSeek API key in a .env file to keep it secure. Create a .env file in the root of your project and add:

REACT_APP_DEEPSEEK_API_KEY=your_api_key_here
Enter fullscreen mode Exit fullscreen mode

Make sure to add .env to your .gitignore file to prevent it from being committed to version control.


Step 3: Create a DeepSeek Service Layer

Create a service layer to handle API requests. This abstracts the API logic from your components and makes it reusable.

Create a file deepseekService.js in the src/services directory:

import axios from 'axios';

const API_KEY = process.env.REACT_APP_DEEPSEEK_API_KEY;
const BASE_URL = 'https://api.deepseek.com/v1/search';

const headers = {
  'Authorization': `Bearer ${API_KEY}`,
  'Content-Type': 'application/json',
};

export const search = async (query, context) => {
  try {
    const response = await axios.post(
      BASE_URL,
      {
        query,
        context,
      },
      { headers }
    );
    return response.data;
  } catch (error) {
    console.error('Error fetching search results:', error);
    throw error;
  }
};
Enter fullscreen mode Exit fullscreen mode

Step 4: Build the Search Component

Now, create a React component to handle user input and display search results. Name it DeepSeekSearch.js.

import React, { useState } from 'react';
import { search } from '../services/deepseekService';

const DeepSeekSearch = () => {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState([]);
  const [loading, setLoading] = useState(false);

  const handleSearch = async () => {
    if (!query.trim()) return;

    setLoading(true);
    try {
      const data = await search(query, 'web'); // 'web' is the context
      setResults(data.results);
    } catch (error) {
      console.error('Search failed:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <input
        type="text"
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        placeholder="Enter your query..."
      />
      <button onClick={handleSearch} disabled={loading}>
        {loading ? 'Searching...' : 'Search'}
      </button>

      <div>
        {results.map((result, index) => (
          <div key={index}>
            <h3>{result.title}</h3>
            <p>{result.snippet}</p>
            <a href={result.url} target="_blank" rel="noopener noreferrer">
              Learn More
            </a>
          </div>
        ))}
      </div>
    </div>
  );
};

export default DeepSeekSearch;
Enter fullscreen mode Exit fullscreen mode

Step 5: Integrate the Component into Your App

Import and use the DeepSeekSearch component in your main application file (App.js):

import React from 'react';
import DeepSeekSearch from './components/DeepSeekSearch';

function App() {
  return (
    <div className="App">
      <h1>DeepSeek R1 Search Integration</h1>
      <DeepSeekSearch />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Step 6: Test the Integration

Run your React app using npm start and verify the integration. Enter a search query in the input field and ensure results are displayed correctly.


Step 7: Optimize and Enhance

Here are some additional enhancements you can implement:

Add Debouncing

To avoid making excessive API calls, implement debouncing using lodash.debounce:

import { debounce } from 'lodash';

...

const handleSearch = debounce(async () => {
  if (!query.trim()) return;

  setLoading(true);
  try {
    const data = await search(query, 'web');
    setResults(data.results);
  } catch (error) {
    console.error('Search failed:', error);
  } finally {
    setLoading(false);
  }
}, 300); // 300ms delay
Enter fullscreen mode Exit fullscreen mode

Handle Pagination

DeepSeek R1 supports pagination. Modify the search function to accept pagination parameters:

export const search = async (query, context, page = 1) => {
  try {
    const response = await axios.post(
      BASE_URL,
      {
        query,
        context,
        page,
      },
      { headers }
    );
    return response.data;
  } catch (error) {
    console.error('Error fetching search results:', error);
    throw error;
  }
};
Enter fullscreen mode Exit fullscreen mode

Update the component to handle pagination:

const [page, setPage] = useState(1);

const handleNextPage = () => {
  setPage(page + 1);
  handleSearch();
};
Enter fullscreen mode Exit fullscreen mode

Conclusion

By following this guide, you’ve successfully integrated DeepSeek R1 into your React app, enabling advanced, context-aware search functionality. This implementation can be further customized to suit your application’s needs, such as filtering results, handling errors gracefully, or integrating with other APIs.

Experiment with DeepSeek R1’s features and explore its documentation to unlock its full potential. Happy coding!


🚀 Stop Writing Boilerplate Prompts

If you want to skip the setup and code 10x faster with complete AI architecture patterns, grab my Senior React Developer AI Cookbook ($19). It includes Server Action prompt libraries, UI component generation loops, and hydration debugging strategies.

Browse all 10+ developer products at the Apollo AI Store | Or snipe Solana tokens free via @ApolloSniper_Bot.

Top comments (0)