More about State

Creating further examples of stateful components with the useState hook.

Learning Goals

At the end of this Tutorial, you will be able to:

  • Add various components for updating numbers, strings and objects to a ReactJS app.

Adding stateful components

In this Lesson you will add some more stateful components to the counter app you built in the previous State and Hooks Lesson.

A component to update a number

Follow the steps below.

  1. To your app from the previous Lesson, add a new component named DoubleNumber.jsx with the following code.
    import { useState } from 'react';
    	
    function DoubleNumber() {
       const [number, setNumber] = useState(4);
    
       function handleDoubleNumber() {
          setNumber(number * 2);
       }
    	
       return (
    	<>
    	   <span>{number}</span>
    	   <button onClick={handleDoubleNumber}>Double the number</button>
    	</>
     )
    }
    	
    export default DoubleNumber;

A component to update text

Follow the steps below.

  1. To your app from the previous Lesson, add a new component named TextUpdater.jsx with the following code.
    import { useState } from 'react';
    
    function TextUpdater() {
    	// Initialize state with a default value
    	const [text, setText] = useState('Initial text');
     
    	function HandleUpdateText() {
    	   setText('Updated text');
    	}
     
    	return (
    	   <>
    		  <span>{text}</span>
    		  <button onClick={HandleUpdateText}>Update Text</button>
    	   </>
       );
     }
     
     export default TextUpdater;
  2. Next, amend the component with an if ... else clause so that it can detect the current text value, and change it to the alternative.
  3. Finally, update the App.jsx file as follows:
    import IncrementDecrement from './IncrementDecrement';
    import DoubleNumber from './DoubleNumber';
    import TextUpdater from './TextUpdater';
    	
    import './Counter.css'
    	
    function App() {
    	  return (
    		<div className="box-counter">
    		  <IncrementDecrement />
    		  <DoubleNumber />
    		  <TextUpdater />
    		</div>
    	  )
    	}
    	
    export default App