What are some good ways to structure React projects and separate logic from every component

0 votes
Can you tell me What are some good ways to structure React projects and separate logic from every component?
Mar 11 in Node-js by Ashutosh
• 23,230 points
55 views

1 answer to this question.

0 votes

Here are some good ways to structure a React project and separate logic from components:

1. Organized Folder Structure

/src

  /components     # Reusable UI components

  /pages          # Page-specific components

  /hooks          # Custom hooks for reusable logic

  /contexts       # Context API for global state

  /services       # API calls, authentication logic

  /utils          # Utility functions

  /store          # Redux/Zustand store (if used)

  /styles         # Global styles

  /assets         # Images, icons, fonts

2. Separate Logic Using Custom Hooks

// hooks/useFetch.js

import { useState, useEffect } from "react";

const useFetch = (url) => {

  const [data, setData] = useState(null);

  useEffect(() => {

    fetch(url)

      .then((res) => res.json())

      .then((data) => setData(data));

  }, [url]);

  return data;

};

export default useFetch;

3. Use Context API or State Management

Avoid prop drilling by using React Context or Redux/Zustand.

4. Move API Calls to a Separate Service Layer

// services/api.js

export const fetchUsers = async () => {

  const response = await fetch("/api/users");

  return response.json();

};

5. Utility Functions for Reusable Logic

// utils/formatDate.js

export const formatDate = (date) => new Date(date).toLocaleDateString();

answered Mar 11 by Tanmay

Related Questions In Node-js

0 votes
1 answer
0 votes
1 answer

What methods are available to force a component to re-render when using React hooks?

Here are the primary methods available to ...READ MORE

answered Feb 23 in Node-js by Kavya
93 views
0 votes
1 answer
0 votes
1 answer

What is the best way to handle e and props in React TypeScript?

In React with TypeScript, handling events and ...READ MORE

answered Feb 23 in Node-js by Kavya
117 views
0 votes
1 answer
0 votes
1 answer

What is the difference between Node.js and Express.js?

Feature Node.js Express.js Definition A runtime environment for executing JavaScript outside ...READ MORE

answered Mar 11 in Node-js by Tanmay
62 views
0 votes
1 answer
0 votes
1 answer

What are the approaches to testing in React?

Testing in React ensures your components, logic, ...READ MORE

answered Dec 12, 2024 in Node-js by Navya
116 views
0 votes
1 answer

What are the limitations of React Native?

React Native is a popular framework for ...READ MORE

answered Dec 12, 2024 in Node-js by Navya
128 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP