'Is this a good way to make a global context?

https://pastebin.com/mUs0bnb9

import { createContext, useState, useEffect } from "react";
 
export const TodoContext = createContext();
 
export const TodoProvider = ({ children }) => {
  const [todos, setTodos] = useState([]);
 
  useEffect(() => {
    setTodos(JSON.parse(localStorage.getItem("todoArray")));
  }, []);
 
  useEffect(() => {
    localStorage.setItem("todoArray", JSON.stringify(todos));
  }, [todos]);
 
  let props = {
    todos,
    removeTodo: (inputId) =>
      setTodos((prevTodos) => prevTodos.filter(({ id }) => inputId === id)),
    addTodo: (inputObj) => setTodos((prevTodos) => [...prevTodos, inputObj]),
  };
 
  return <TodoContext.Provider value={props}>{children}</TodoContext.Provider>;
};

Would this be appropriate use of the Context API?

Well, I did above code. Is this a good way to do it?



Solution 1:[1]

Your code is good, it is right.

Context API is very used, but the last projects we are using Recoil.JS, its more easy and better to work with, and its already in stable version.

We dont use too much Redux, Mobx anymore, so context and recoil is the best options.

Take a look in a Recoil documentation, and see if it fits on your needs.

Resuming, your context is right, but i prefer to use recoil.

Cheers !

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jhony Spark