Consider the following React components. What will be displayed on the screen?
import React, { useState } from 'react'; function Child({ message }) { return <p>{message}</p>; } export default function Parent() { const [msg] = useState('Hello from Parent'); return <Child message={msg} />; }
Look at how the message prop is passed from Parent to Child.
The Parent component passes the msg state as a prop named message to the Child. The Child renders this prop inside a paragraph, so the output is the string 'Hello from Parent'.
In this React component, what will be the value of count after the button is clicked once?
import React, { useState } from 'react'; function Child({ onClick }) { return <button onClick={onClick}>Click me</button>; } export default function Parent() { const [count, setCount] = useState(0); return <> <p>{count}</p> <Child onClick={() => setCount(count + 1)} /> </>; }
Check how the onClick function updates the state in the Parent.
The Parent component holds the count state starting at 0. The Child receives a function to increment count. Clicking the button calls this function, increasing count to 1.
Look at this React code. The Parent updates its state, but the Child does not show the new value. Why?
import React, { useState, useMemo } from 'react'; function Child({ value }) { return <p>{value}</p>; } export default function Parent() { const [count, setCount] = useState(0); const val = useMemo(() => count, []); return <> <button onClick={() => setCount(count + 1)}>Increment</button> <Child value={val} /> </>; }
Think about what causes React components to re-render and memoized values to recompute.
Option D is correct. The val uses useMemo(() => count, []) with an empty dependency array, so it caches the initial count (0) and never recomputes. Parent re-renders on count change (re-rendering Child), but value={val} stays 0 since val is not state and doesn't update. Other options are incorrect: button has onClick, prop passed correctly, setCount called.
Which of these code snippets correctly passes a callback function from a Parent component to a Child component in React?
Remember to pass the function itself, not the result of calling it.
Option A passes the function handleClick as a prop correctly. Option A calls the function immediately and passes its result (undefined). Option A tries to call the JSX element, which is invalid. Option A passes a function that returns the function, not the function itself, so the Child's onClick will not behave as expected.
You want a Child component to update the Parent's state. Which approach follows React's recommended pattern?
Think about how React encourages data flow and state management.
React recommends passing state setter functions down as props to children that need to update parent state. Direct modification or refs break React's data flow and can cause bugs. Context is for sharing data but not for direct state updates.