heaks
heaks

Reputation: 77

React 16 read state issue

I have the following component

import React, { useState } from 'react';

const Test = () => {
    const [streaming, setStreaming] = useState(false);
    
    const turnStreamingOn = () => {
        setStreaming(true);
        process();
    }
    
    const process = () => {
        console.log('streaming:', streaming);
    }
    
    return (
        <div>
            <button onClick={() => {
                turnStreamingOn();
            }}>{streaming ? 'streaming' : 'not streaming'}</button>
        </div>
    )
};

export default Test;

on button click, we have 'streaming' in UI, but console.log in 'process' function says it's false. What am I doing wrong? How to read the state properly?

Upvotes: 1

Views: 55

Answers (1)

Henok Tesfaye
Henok Tesfaye

Reputation: 9560

import React, { useEffect, useState } from 'react';

const Test = () => {
    const [streaming, setStreaming] = useState(false);
    
    const turnStreamingOn = () => {
        setStreaming(true);
    }

    useEffect(() => {
      console.log('streaming: ', streaming)
    }, [streaming])
    
    return (
        <div>
            <button onClick={() => {
                turnStreamingOn();
            }}>{streaming ? 'streaming' : 'not streaming'}</button>
        </div>
    )
};

export default Test;

You should use useEffect for this purpose.

Upvotes: 3

Related Questions