React useState callback tutorial

React useState callback tutorial

Hello! In this section, you’re going to learn about how to use a callback with the useState hook. As part of the class component, we could pass a second argument to the setState function. However, the setState function returned by theuseState hook in the functional component does not take an extra argument.

Introduction to useState

In the old “class” oriented React version you could call setState and pass it as a second argument function which would be called when the state of the component would be updated. But with the new “functional” oriented React, where you described components using plain functions, you should use the useState hook to track the internal component’s state inside the function.

Let’s start with how we will proceed with the topic.

class App extends React.Component {
	constructor() {
		super();
		this.state = { key: "value" };
	}

	updateState() {
		this.setState("new-value", () => 
			console.log("value :" + this.state.key)
		})	
	}
	
	render() {
		// jsx	
	}
}
Code language: JavaScript (javascript)

React useState callback

In React, useState is a hook function that allows us to have state variables in a functional component. The useState hook takes an initial value as its argument or function as an argument if the initial state has to be computed.

const [state, setState] = useState(initialstate)
// OR
const [state, setState] = useState(function getState() {
	return newState;
});
Code language: JavaScript (javascript)

We can attach an useEffect to a state variable and run a function every time the variable is modified.

useEffect(() => {}, [state]);Code language: JavaScript (javascript)

Example (with useEffect)

const [age, setAge] = React.useState(0);

React.useEffect(() => {
  if (age > 18) {
    console.log('You are old enough!.');
  } else {
    console.log('Oh no, too young.');
  }
}, [age]);
Code language: JavaScript (javascript)

Example (with an NPM package)

Here is a package that contains useState a callback function. Check it out here.

import useStateWithCallback from 'use-state-with-callback';

const [age, setAge] = useStateWithCallback(0, age => {
	if (age > 18) {
    console.log('You are old enough!.');
  } else {
    console.log('Oh no, too young.');
  }
});
Code language: JavaScript (javascript)

Conclusion

You will inevitably get stuck at some point in the curriculum, perhaps due to a concept that you are having difficulty understanding or perhaps due to something not working correctly in a project. Whatever it is, make sure you take the required breaks, ask for help, or just simply google it!

Thank you for taking the time to look around and read more than just one blog! Wishing you all the best!

Sharing is caring

Did you like what Jainam Desai wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far