DEV Community

Apollo
Apollo

Posted on

How to integrate DeepSeek R1 into your React app

Integrating DeepSeek R1 into Your React App

DeepSeek R1 is a cutting-edge AI-powered search and recommendation engine that enables developers to add intelligent, context-aware search capabilities to their applications. In this tutorial, we’ll walk through the process of integrating DeepSeek R1 into a React app, complete with real-world code snippets and best practices.


Prerequisites

Before we begin, ensure you have the following:

  1. A DeepSeek R1 API key (sign up at DeepSeek).
  2. A React project set up with npm or yarn.
  3. Node.js installed on your machine.

Step 1: Install Required Dependencies

First, install the necessary dependencies for making API requests and handling state in your React app.

npm install axios @tanstack/react-query
Enter fullscreen mode Exit fullscreen mode
  • axios: A popular HTTP client for making API requests.
  • @tanstack/react-query: A powerful library for managing asynchronous data fetching and caching.

Step 2: Set Up Your DeepSeek R1 Client

Create a utility file to handle DeepSeek R1 API requests. This will encapsulate the logic for interacting with the API.

// src/utils/deepseek.js
import axios from 'axios';

const DEEPSEEK_API_URL = 'https://api.deepseek.ai/v1';
const apiKey = process.env.REACT_APP_DEEPSEEK_API_KEY;

const deepseekClient = axios.create({
  baseURL: DEEPSEEK_API_URL,
  headers: {
    'Authorization': `Bearer ${apiKey}`,
    'Content-Type': 'application/json',
  },
});

export const search = async (query, context = {}) => {
  try {
    const response = await deepseekClient.post('/search', {
      query,
      context,
    });
    return response.data.results;
  } catch (error) {
    console.error('DeepSeek R1 search error:', error);
    throw error;
  }
};
Enter fullscreen mode Exit fullscreen mode

Step 3: Create a React Hook for DeepSeek Search

To make DeepSeek R1 search functionality reusable across components, create a custom React hook using @tanstack/react-query.

// src/hooks/useDeepseekSearch.js
import { useQuery } from '@tanstack/react-query';
import { search } from '../utils/deepseek';

export const useDeepseekSearch = (query, context = {}) => {
  return useQuery(['deepseekSearch', query], () => search(query, context), {
    enabled: !!query, // Only run the query if there's a search term
    staleTime: 1000 * 60 * 5, // Cache results for 5 minutes
  });
};
Enter fullscreen mode Exit fullscreen mode

Step 4: Build the Search Component

Now, create a search component that uses the useDeepseekSearch hook to fetch and display results.

// src/components/Search.js
import React, { useState } from 'react';
import { useDeepseekSearch } from '../hooks/useDeepseekSearch';

const Search = () => {
  const [query, setQuery] = useState('');
  const { data: results, isLoading, isError } = useDeepseekSearch(query);

  const handleSearch = (e) => {
    e.preventDefault();
    setQuery(e.target.value);
  };

  return (
    <div>
      <input
        type="text"
        placeholder="Search..."
        value={query}
        onChange={handleSearch}
      />
      {isLoading && <p>Loading...</p>}
      {isError && <p>Error fetching results</p>}
      {results && (
        <ul>
          {results.map((result, index) => (
            <li key={index}>{result.title}</li>
          ))}
        </ul>
      )}
    </div>
  );
};

export default Search;
Enter fullscreen mode Exit fullscreen mode

Step 5: Add Contextual Search Support

DeepSeek R1 excels at contextual search, leveraging additional metadata to refine results. Modify the Search component to include contextual information.

const Search = () => {
  const [query, setQuery] = useState('');
  const [context, setContext] = useState({ category: 'technology' });

  const { data: results, isLoading, isError } = useDeepseekSearch(query, context);

  const handleCategoryChange = (e) => {
    setContext({ ...context, category: e.target.value });
  };

  return (
    <div>
      <select value={context.category} onChange={handleCategoryChange}>
        <option value="technology">Technology</option>
        <option value="finance">Finance</option>
        <option value="health">Health</option>
      </select>
      <input
        type="text"
        placeholder="Search..."
        value={query}
        onChange={(e) => setQuery(e.target.value)}
      />
      {isLoading && <p>Loading...</p>}
      {isError && <p>Error fetching results</p>}
      {results && (
        <ul>
          {results.map((result, index) => (
            <li key={index}>{result.title}</li>
          ))}
        </ul>
      )}
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Step 6: Display Rich Search Results

DeepSeek R1 often returns rich data, such as descriptions, images, and links. Enhance the Search component to display these details.

{results && (
  <ul>
    {results.map((result, index) => (
      <li key={index}>
        <h3>{result.title}</h3>
        {result.image && <img src={result.image} alt={result.title} />}
        <p>{result.description}</p>
        <a href={result.link} target="_blank" rel="noopener noreferrer">
          Learn More
        </a>
      </li>
    ))}
  </ul>
)}
Enter fullscreen mode Exit fullscreen mode

Step 7: Optimize for Performance

To improve performance:

  1. Debounce the search input to reduce API calls.
  2. Use React.memo to memoize the Search component.
import { useState } from 'react';
import { debounce } from 'lodash';
import { useDeepseekSearch } from '../hooks/useDeepseekSearch';

const Search = () => {
  const [query, setQuery] = useState('');
  const debouncedSetQuery = debounce(setQuery, 300);

  const { data: results, isLoading, isError } = useDeepseekSearch(query);

  return (
    <div>
      <input
        type="text"
        placeholder="Search..."
        onChange={(e) => debouncedSetQuery(e.target.value)}
      />
      {isLoading && <p>Loading...</p>}
      {isError && <p>Error fetching results</p>}
      {results && (
        <ul>
          {results.map((result, index) => (
            <li key={index}>{result.title}</li>
          ))}
        </ul>
      )}
    </div>
  );
};

export default React.memo(Search);
Enter fullscreen mode Exit fullscreen mode

Conclusion

By following this tutorial, you’ve successfully integrated DeepSeek R1 into your React app, enabling powerful, context-aware search capabilities. This implementation leverages modern libraries like axios and @tanstack/react-query to ensure efficiency and maintainability.

DeepSeek R1’s flexibility and intelligence allow you to build highly customized search experiences tailored to your app’s needs. Experiment with different contexts and optimize the UI to deliver a seamless user experience. 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)