Organizing Code with React Hooks and Context

When working on large-scale React projects, it's crucial to have a well-organized codebase for better maintainability and scalability.

In this article, we will dive into the best practices for organizing your source code in React, with a focus on utilizing React Hooks and Context.

 

Using React Hooks for State Management

React Hooks are a collection of functions that allow you to use state and other React features without using classes. This helps to write more concise and readable code. For example, we can use the useState Hook to manage state in a component.

Here is an example:

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

export default Counter;

 

Combination of ingredients

One of the benefits of React is the ability to reuse components. To increase organization, we can use smaller components to build larger components.

This helps to break down the work and make code easy to maintain. For example, we can create a <Button> component to use in multiple places in our application:

import React from 'react';

function Button({ onClick, children }) {
  return <button onClick={onClick}>{children}</button>;
}

export default Button;

 

Using Context to manage global state

Context is a mechanism in React that allows us to share data between child components without passing through parent components. This avoids passing data attributes across multiple component levels and helps reduce code complexity.

Here is an example of using Context to share the current language in the application:

import React, { createContext, useContext, useState } from 'react';

const LanguageContext = createContext();

function App() {
  const [language, setLanguage] = useState('en');

  const changeLanguage = (newLanguage) => {
    setLanguage(newLanguage);
  };

  return (
    <LanguageContext.Provider value={{ language, changeLanguage }}>
      <div>
        <Navbar />
        <Content />
      </div>
    </LanguageContext.Provider>
  );
}

function Navbar() {
  const { language, changeLanguage } = useContext(LanguageContext);

  return (
    <div>
      <button onClick={() => changeLanguage('en')}>English</button>
      <button onClick={() => changeLanguage('fr')}>French</button>
      <button onClick={() => changeLanguage('es')}>Spanish</button>
      <p>Current language: {language}</p>
    </div>
  );
}

function Content() {
  const { language } = useContext(LanguageContext);

  return <p>This is the content in {language}.</p>;
}

export default App;

 

Above are some best practices for organizing React source code using React Hooks and Context.