Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 26, 2020 03:33 am GMT

How to Replace Redux with React Context

Why Not Redux?

Redux when it was released was a great tool. It was a bit hard to initially wrap your head around and verbose, but it got the job done well. These days, it probably isn't your best choice unless your app gets a lot of value from replayability or time rewinding (maybe a game?).

What state management these days are worth investing in? Well, I would argue none. Just use the react API itself.

How?

// ...importsconst Context = createContext({})const TodoProvider = ({children}) => {  const [todos, setTodos] = useState({})  const addTodo = (todo) => {    setTodos(old => ({...old, [todo.id]: todo})  }  const editTodo = (todo) => {    setTodos(old => ({...old, [todo.id]: {...old[todo.id], todo}}))  }  return <Context.Provider value={{editTodo, addTodo, todos}}>{children}</Context.Provider>}export default TodoProviderexport {Context as todoContext}

and then consume inside a component:

const {addTodo, editTodo, todos} = useContext(todoContext)

Boom! You have a local provider. Just import todoContext and you are off! simple enough! Just make sure that the thing you are importing is a child of the provider, meaning that the consumer is included as part of the children prop of TodoProvider.

This isn't particularly new or exciting. Unless you hate are looking to replace redux in your app, then this is quite exciting.

Here is a working short example: https://codesandbox.io/s/exciting-swartz-ev560

Photo by chuttersnap on Unsplash

Follow me on twitter @bwighthunter or here on dev.to I write about other topics as well on medium.


Original Link: https://dev.to/bwighthunter/how-to-replace-redux-with-react-context-4h3c

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To