Human Cyborg Relations
Human Cyborg Relations

Reputation: 1244

React setState not triggering a re-render with Contexts

I've got a React component that updates its state after making a request. In the render function of this component, I am creating a context provider and passing in the value of the state.

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            text: 'defaultValue',
        }
    }

    componentDidMount() {
        makeAxiosRequest()
        .then((response) => {
            this.setState({
                text: 'updatedValue'
            })
        })
        .catch((error) => {
            console.log(error)
        }) 
    }

    render() {
        console.log(this.state.text)
        return (
            <div>
                <MyContext.Provider value={{
                    text: this.state.text
                }}>
                    <SomeComponent />
                </MyContext.Provider>
            </div>
        )
    }
}

export default App;

Then, In the child component, I am trying to get that value from the context.

class SomeComponent extends React.Component {
    static contextType = MyContext;
    constructor(props, context) {
        super(props, context);
        console.log(this.context.text)
    }
}

However, the value in the context in SomeComponent is 'defaultValue', instead of the updated value.

The final console log is:

defaultValue
defaultValue
updatedValue

Shouldn't it instead be

defaultValue
defaultValue
updatedValue
updatedValue

because when the value is updated, then a re-render should be triggered and context should be updated. What am I missing here?

Upvotes: 1

Views: 199

Answers (1)

Daniel Bank
Daniel Bank

Reputation: 3899

SomeComponent's constructor() only gets called when the component mounts, not when it re-renders. In order to see the new context value you would need to put your console.log(this.context.text) inside its render() or a lifecycle method like componentDidUpdate().

Upvotes: 1

Related Questions