I was playing around with useContext in a class component. I've created a simple react (nextjs) application with one button that call a function in the context that update the state and therefore re-render the home component.
import { useContext } from "react";
import { UserContext } from "../provider/TestProvider";
export default function Home() {
let [contex] = useContext(UserContext);
// Without the destructuring assignment
// let contex = useContext(UserContext);
return (
<>
<button onClick={() => contex.addOne()}>Add 1</button>
{contex.state.count.map((e) => (
<div key={Math.random()}> {e} </div>
))}
</>
);
}
import { createContext, Component } from "react";
export const UserContext = createContext();
export default class TestProvider extends Component {
state = {count: []};
constructor(props) {
super(props);
this.props = props;
}
addOne() {
let oldState = [...this.state.count];
oldState.push("test");
this.setState({ count: oldState });
}
render() {
return ( // Changing value to value={this}
<UserContext.Provider value={[this]}>
{this.props.children}
</UserContext.Provider>
);
}
}
Note: The provider it's wrapped to the entire application, inside
_app.js
this is working fine, however I was wondering why I'm forced to pass
this inside an array?
value={[this]}
When I tried to pass only this (value={this}) and modify the context
let contex = useContext(UserContext)
the Home function doesn't react anymore on the change of the state, and therefore no rerender.
From my knowledge of programming both options should behave exactly the same.
What is happening here?