Home > Enterprise >  Is this a good way to make a global context?
Is this a good way to make a global context?

Time:03-24

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?

CodePudding user response:

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 !

  • Related