0

So after coding a complete web application with react with props-drilling so deep like you've never seen before, I've decided to give react 'contexts' a go. I read the react documentation, and I've decided to use the following approach to make my states(which seriously need help because they're so deeply rooted into components after components) global

-create a 'context.js' file .

-Inside I'm gonna have: [and notice I have two states inside]

import { createContext } from 'react'
export const context = createContext();
export default function ContextProvider (props) {
    const [state1, setState1] = useState();
    const [state2, setState2] = useState();
    return (
        <context.provider value={[state1, setState1, state2, setState2]}>
            props.children
        </context.provider>
       )
}
  • Now all I have to do is import this component where I want to make these states visible, use destructuring like so:
//inside a functional component
...
const [state1, setState1] = useContext(context); //assuming I only need state1 in this component
...

Now my question is how efficient this approach is. I don't thinks it is, because if I called the setState1 function, then all the child components would re-render. Or is react advanced enough to handle such state changes efficiently. I really need an insight on this. That'll be appreciated.

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118

1 Answers1

1

It's not the most efficient way because every time state changes, things will get rendered again. You have no way to avoid this, unfortunately.

The above applies for useReducer as well.