Lädt...

🔧 Beginner's Guide to Writing Cleaner React Code with TanStack-Query


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

Showing data obtained from external sources is a fundamental

Here are the steps to start using React Query to enhance your code:

1.Understand the difference between client state and server state

Client state exists in the browser, such as form state, dark mode, or whether a modal is open or closed. Server state probably resides in a database and is served asynchronously.

Always use React Query for server state. For client state, use native hooks like useState or useReducer.

2. Install React-Query in your project

Follow the installation instructions and remember to set up the query client provider

3. Replace data fetching code and states in your code with the useQuery hook Instead of writing this:

 const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function fetchData() {
      try {
        const response = await fetch('https://rickandmortyapi.com/api/character');
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        const result = await response.json();
        setData(result.results);
      } catch (err) {
        setError(err);
      } finally {
        setLoading(false);
      }
    }

    fetchData();
  }, []);

write this:

function fetchRickAndMortyCharacters() {
  return fetch('https://rickandmortyapi.com/api/character')
    .then(response => {
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      return response.json();
    })
    .then(data => data.results);
}

  const { data, isLoading, isError, error } = useQuery(['rickAndMortyCharacters'], fetchRickAndMortyCharacters);

The data you need to render will be in the destructured data. Here is an example of how you can render the result:

 if (isLoading) return <p>Loading...</p>;
  if (isError) return <p>Error: {error.message}</p>;
  if (!data) return <p>No data available</p>;

  return (
    <ul>
      {data.map(character => (
        <li key={character.id}>{character.name}</li>
      ))}
    </ul>
  );

4.Convert the useQuery hook into a custom hook

For better reusability, abstract this into a custom hook:

export function useRickAndMortyCharacters() {
  return useQuery(['rickAndMortyCharacters'], fetchRickAndMortyCharacters);
}

now, from any component, you can just call the custom hook like so:

const { data, isLoading, isError, error } = useRickAndMortyCharacters();

That's it! If you want to go any further, read the docs and play around with different query options or with mutations.

Thanks for reading!

...

🔧 Writing Cleaner React Components: A Practical Guide


📈 33.53 Punkte
🔧 Programmierung

🔧 Important React Tips for Writing Cleaner, Efficient Code for Beginners


📈 32.47 Punkte
🔧 Programmierung

🔧 Writing cleaner code with Tailwind CSS in React


📈 32.47 Punkte
🔧 Programmierung

🔧 Formik &amp; React: Writing Cleaner, More Efficient Forms


📈 29.09 Punkte
🔧 Programmierung

🔧 A complete guide to TanStack Table (formerly React Table)


📈 28.29 Punkte
🔧 Programmierung

🔧 Ultimate Guide to Integrating React Hook Form with TanStack Start


📈 28.29 Punkte
🔧 Programmierung

🔧 Design Patterns #5: Null Object Pattern – Writing Safer, Cleaner Code.


📈 26.8 Punkte
🔧 Programmierung

🔧 PHP Tips and Tricks for Writing Cleaner and More Efficient Code


📈 26.8 Punkte
🔧 Programmierung

🔧 Understanding Object Calisthenics: Writing Cleaner Code


📈 26.8 Punkte
🔧 Programmierung

🔧 🧹 Essential Tips for Writing Cleaner Code: Keep It Simple! ✨


📈 26.8 Punkte
🔧 Programmierung

🔧 Writing Pythonic Code: Tips and Tricks for Cleaner Syntax.


📈 26.8 Punkte
🔧 Programmierung

🔧 Writing cleaner Jetpack Compose code with the Twitter Compose Ruleset


📈 26.8 Punkte
🔧 Programmierung

🐧 Clever Cleaner for iPhone Review: 100% Free, Ad-Free iOS Cleaner App


📈 26.64 Punkte
🐧 Linux Tipps

🍏 AnyMP4 iOS Cleaner 1.0.18 - iOS cleaner.


📈 26.64 Punkte
🍏 iOS / Mac OS

📰 'Say hello to my little vacuum cleaner!' US drug squad puts spycams in cleaner's kit


📈 26.64 Punkte
📰 IT Security Nachrichten

📰 'Say hello to my little vacuum cleaner!' US drug squad puts spycams in cleaner's kit


📈 26.64 Punkte
📰 IT Security Nachrichten

🔧 Beginner’s Guide to Writing Clean Java Code


📈 26.19 Punkte
🔧 Programmierung

🔧 Java Functions/Methods: A Beginner's Guide to Writing Efficient Code


📈 26.19 Punkte
🔧 Programmierung

🔧 Writing Your First JavaScript Code: A Beginner's Guide


📈 26.19 Punkte
🔧 Programmierung

🔧 Technical Writing Guide: Introduction to Technical Writing and Its Tools


📈 24.62 Punkte
🔧 Programmierung

🔧 Sniffing Out Code Smells and Design Smells: A Guide to Cleaner Code | Web Theory: Part 13


📈 24.54 Punkte
🔧 Programmierung

🔧 Understanding AI ReAct: A Beginner's Guide to the ReAct Framework


📈 24.07 Punkte
🔧 Programmierung

🔧 React Hooks Tutorial: A Beginner’s Guide to Modern React Development


📈 24.07 Punkte
🔧 Programmierung

🔧 From React to React Native – A Beginner-Friendly Guide🚀


📈 24.07 Punkte
🔧 Programmierung

🔧 Beginner Guide on Unit Testing in React using React Testing Library and Vitest


📈 24.07 Punkte
🔧 Programmierung