Simple Way To Use React Hooks With Context For State Management

Simple Way To Use React Hooks With Context For State Management

This one file will show you from start to finish how to make a simple state management system using only React Hooks & Context.

My hope is that this barebones example will help you understand how the fundamental pieces are interconnected which will allow you to build on to it from there.

Option 1: Play in CodeSandbox

Option 2: Check out the code

Usually you'd break these pieces of code up into different files and import them when needed.

For this example I kept the code together in one file, but I added comments to show which separate files they would belong to if you were to split them up.

import React from "react";
import ReactDOM from "react-dom";

// StoreContext.js
const StoreContext = React.createContext();

// App.js
function App() {
  const { ingredientStore } = React.useContext(StoreContext);
  const { ingredients, setIngredients } = ingredientStore;
  const [newIngredient, setNewIgredient] = React.useState("");
  const handleNewIngredient = () => {
    setIngredients(state => [...state, newIngredient]);
    setNewIgredient("");
  };

  const renderIngredient = ingredient => <li key={ingredient}>{ingredient}</li>;

  return (
    <>
      <h1>Ingredients</h1>
      <label htmlFor="ingredient">Add New Ingredient: </label>
      <input
        name="ingredient"
        onChange={ev => setNewIgredient(ev.target.value)}
        type="text"
        value={newIngredient}
      />{" "}
      <button onClick={handleNewIngredient}>Add</button>
      <ul>{ingredients.map(renderIngredient)}</ul>
    </>
  );
}

// useIngredientStore.js
const useIngredientsStore = () => {
  const [ingredients, setIngredients] = React.useState(["Noodles", "Sauce"]);
  return {
    ingredients,
    setIngredients
  };
};

// StateProvider.js
function StateProvider({ children }) {
  const ingredientStore = useIngredientsStore();
  const store = { ingredientStore };
  return (
    <StoreContext.Provider value={store}>{children}</StoreContext.Provider>
  );
}

// index.js
const rootElement = document.getElementById("root");
ReactDOM.render(
  <StateProvider>
    <App />
  </StateProvider>,
  rootElement
);