You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
What do you think of this API? It's a very simple change to the library, but personally I find it more elegant.
importReact,{useState,useContext}from"react";importcreateContainerfrom"constate";// 1️⃣ Create a custom hook as usualconstuseCounter=()=>{const[count,setCount]=useState(0);constincrement=()=>setCount(prevCount=>prevCount+1);return{ count, increment };}// 2️⃣ When you need to share your state, simply wrap your hook// with the createContainer higher-order hook, like so:constuseCounter=createContainer(()=>{// ... same logic here});functionButton(){// 3️⃣ Use the same hook like you were before, with the same api. No change.const{ increment }=useCounter()return<buttononClick={increment}>+</button>;}functionCount(){// 4️⃣ But now you can use it in other components as well.const{ count }=useCounter()return<span>{count}</span>;}functionApp(){// 5️⃣ The caveat, you wrap your components with the Provider that is// attached to the hookreturn(<useCounter.Provider><Count/><Button/></useCounter.Provider>);}
The change in the code is roughly this (the last 3 lines specifically):
exportfunctioncreateContainer(useValue,createMemoInputs){constContext=React.createContext()constProvider=props=>{constvalue=useValue(props)const{ children }=propsconstmemoizedValue=createMemoInputs ? React.useMemo(()=>value,createMemoInputs(value)) : valuereturn<Context.Providervalue={memoizedValue}>{children}</Context.Provider>}consthook=()=>useContext(Context)hook.Provider=Providerreturnhook}
The text was updated successfully, but these errors were encountered:
What do you think of this API? It's a very simple change to the library, but personally I find it more elegant.
The change in the code is roughly this (the last 3 lines specifically):
The text was updated successfully, but these errors were encountered: