Reputation: 51
I recently started using the Context React Api with useContext Hook. I have observed that when we have a state variable i.e. const someState = useState(state, setState), some developers pass setSate directly in the provider values and then calling it in children components. Is that a good practice?
When you do not use context you have to create a handler to "access" setState in a child component. I am still using handler functions and pass them into the provider values, to import them from context in children.
Is passing setState in context a good pracice? I still have some doubts since normally you cannot pass setState directly into a component. Is there any difference in performance or any other drawbacks I should be considering?
Thank you.
Upvotes: 4
Views: 15494
Reputation: 519
you can use state as variable not as spreaded one
const state = useContext(0);
state[0] //it's the getter for state you can access the values from this
(state[1])(10) //it is setter for state you can set values with is
(state[1])((oldvalues)=>{//write you code here})
Upvotes: 0
Reputation: 539
Edit: I actually think I got you wrong, but I'm not sure. My reply is valid for the case if you write your own provider that has a state. If you just use a default provider that provides a setter, I would agree with the reply of Amel.
I personally wouldn't do it, but that's more of an opionion. However, like always, it pretty much depends on what goal you want to reach.
A positive aspect of doing it is, that state setters given by useState always stay the same for each rerender. If you pass a custom value, you should avoid that it changes too often because every component listening to the change using useContext would rerender.
I would still prefer to pass a custom object (e.g. coming from a useMemo to avoid unnecessary rerenders) with a callback to set the state. It's easier to extend if you want to provide more stuff in the future.
Something like this (very simplistic example, that of course doesn't make sense like this, it's just for comprehension):
function MyProvider({children}) {
const [state, setState] = useState(0);
const provided = useMemo(() => ({
value: state,
setValue: (value) => setState(value)
}, [value]);
return <MyContext.Provider value={provided}>{children}</MyContext.Provider>;
}
It would be easier to extend without changing code everyhwere where the context is used. However, I still think there is nothing particular bad in passing just the setter, if that is what you want to achive.
Upvotes: 4
Reputation: 793
If I understood correctly the difference is that in one way the state is set from the parent component and in the other the state is set from the child component. Sometimes people do it that way to avoid loop rendering with changing the state. There should be no drawbacks, but using handler functions is the regular way to go.
Upvotes: 2