Blogs Technology

State management in react – using ContextAPI hooks vs classes

First two steps are same for both hooks and classes

Step 1: Creating context variable from useContext, obviously you need to import useContext.

File Name : “FileContext”
import React from “react”;
export default React.createContext({});

Step 2: Sending functions or variables via props to the context using context.provider, provider will make sure these variables or functions are available for all components in the project if we are doing it in root component.
FileName :app.js(depends on your project)

<FileContext.Provider
value={{
dices,
setDices
}}
>
<div className=”App”>
<Component 1 />
<Component 2 />
<Component 3 />
<Component 4 />
</div>
</FileContext.Provider>

Here in above component 1 may be having more components inside, and these values will be available to all children’s of all these components placed under the provider. Any component outside of the provider will not be having access to these context(dices, setDices) values.

Here we should be smart about in which component we should write this provider, if the values are not used by component 2,3,4 then you should write provider in component 1 only so we can avoid giving access of values to component 2,3,4 where these values are irrelevant.

Step 3 is different for hooks and classes:

inHooks: you can simply assign and access values and functions.
Import FileContext
import useContext
const contextValues = useContext(FileContext);
contextValues.dices
contextValues.setDices
hooks example:(game is incomplete, but state management implemented successfully)
https://lnkd.in/gHH-9d6V

InClass Components : you need to write consumer and make all other components which are using these context values as a children. you need to define component content wrap inside the function.
Import FileContext

import context from ‘./FileContext’;
export default class ProfileScreen extends React.Component {
componentDidMount() {}

render() {
return (
<div>
<FileContext.Consumer>
{context => (
<h3>Hello Again, {profile.fullName}</h3>
)}
</FileContext.Consumer>
</div>
)
}
}

Working on class example, will update this article soon.

#react #management #content #statemanagement