react setstate callback code example

Example 1: pass variable to setstate callback

selectHandler(event){
    const { target } = event;

    this.setState({
        selectedImage: target
    }, () => {
        this.markSelectedHandler(target)
    })
}

markSelectedHandler(target){
    target.classList.add('active')
    if(target!== this.state.selectedImage && this.state.selectedImage){
        this.state.selectedImage.classList.remove('active')
        target.classList.add('active')
    }
}

Example 2: react callback set staet

setState(  { name: "Michael" },  () => console.log(this.state));// => { name: "Michael" }

Example 3: react native class component constructor

import React from 'react';  
import { View, TextInput } from "react-native";

class App extends React.Component {  
  constructor(props){  
    super(props);  
    this.state = {  
         name: "" 
      }  
    this.handleChange = this.handleChange.bind(this);  
  }
  handleChange(text){
    this.setState({ name: text })
    console.log(this.props);  
  }  
  render() {  
    return (  
    <View>
      <TextInput 
      	value={this.state.name} 
  		onChangeText={(text) =>this.handleChange(text)}
      />
    </View>  
  }  
}  
export default App;

Example 4: How to use `setState` callback on react hooks

//You need to use useEffect hook to achieve this.

const [counter, setCounter] = useState(0);

const doSomething = () => {
  setCounter(123);
}

useEffect(() => {
   console.log('Do something after counter has changed', counter);
}, [counter]);

Example 5: react functional components setstate callback

const [state, setState] = useState({ name: "Michael" })
const isFirstRender = useRef(true)

useEffect(() => {
  if (!isFirstRender.current) {
    console.log(state) // do something after state has updated
  }
}, [state])

useEffect(() => { 
  isFirstRender.current = false // toggle flag after first render/mounting
}, [])