Intro to React basics (concept)

Computer Science · JavaScript

Question 1 of 10

0

    Which hook gives you a reference to a DOM element, for example to focus an input?

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Intro to React basics (concept) explained

    React is a JavaScript library for building user interfaces from components. A component is a function that returns a description of part of the screen, and React re-renders a component when the data it depends on changes.

    Component names start with a capital letter. They return JSX, a syntax that looks like HTML and is converted into JavaScript calls before the code runs. Curly braces inside JSX embed any JavaScript expression. Data passed into a component is called props and should be treated as read-only.

    function Counter() {
        const [count, setCount] = useState(0);
        return (
            <button onClick={() => setCount(count + 1)}>
                Clicked {count} times
            </button>
        );
    }
    

    Data that changes over time is kept as state. The useState hook returns the current value and a setter, and calling the setter makes React render again with the new value. Hooks may only be called at the top level of a component. Items in a list need stable keys so React can track them.

    Worked example

    The count starts at 0. After three clicks, count is 3 and the button reads Clicked 3 times. Caveat: if one handler calls setCount(count + 1) three times, the count rises by only one, because each call reads the same old value. Passing a function, setCount(c => c + 1), avoids this.

    What you will practise

    102 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.

    Example questions

    • React builds:
    • Components are:
    • JSX:
    • State:
    • Props are:
    • Which hook adds state to a function component?
    • Which hook runs side effects after rendering, such as fetching data?
    • What does a React component function return?

    …and 94 more.