Optimizing Data Management in React

Data Best Practices

UI Layer in React

Data Layer in React

Key Differences

What are Props?

Difference Between Props and State Variables

Props:

State:

Prop Drilling

What is Prop Drilling?

Context API in React

What is Context API?

How to Use Context API?

  1. Create a Context: Use React.createContext() to create a new context. Usually created in utilsfolder at centeral place.
    const MyContext = React.createContext();
    
  2. Provider Component: Wrap your component tree with the Provider component of the created context. This will pass the data to all components inside the provider.
<MyContext.Provider value={/* some value */}>
  {/* children components */}
</MyContext.Provider>
  1. *Consume the Context: Use the useContext hook or MyContext.Consumer to access the context value in any component within the provider.
const value = useContext(MyContext);

Benefits of Context API

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

// Create a context
const ThemeContext = createContext();

function App() {
  const [theme, setTheme] = useState("light");

  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function Toolbar() {
  const { theme, setTheme } = useContext(ThemeContext);

  return (
    <div>
      <h1>Current Theme: {theme}</h1>
      <button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
        Toggle Theme
      </button>
    </div>
  );
}

export default App;