Answer:
JSX stands for JavaScript XML.
It is a syntax extension for JavaScript that looks like HTML but is used inside JavaScript code.
Why is JSX used?
- JSX allows UI elements to be written in a way that looks a lot like HTML.
- This makes the code more readable and intuitive.
- JavaScript embedded directly inside JSX using { }
- JSX automatically escapes values before rendering them.
- JSX is perfect for React’s component system.
Answer:
Props
Definition: Props are readable input that is passed from a parent to a child component.
Purpose: Used to pass data to a component.
Mutable? No, it is immutable. A component cannot change its own props.
Similar to function parameters.
State
Definition: State is a component's own local data, which is managed within that component.
Purpose: Data changes over time. E.g. user input, API data, toggle values. State is used to store data.
Mutable?: The data in State is mutable. A component can update its own state with setState or useState.
Similar to variables declared inside a function, but React keeps track of them across renders.
Answer: useState is a React Hook that allows adding state to functional elements. Re renders component when state changes. Does not merge automatically. If objects or arrays are stored, they need to be spread out when updating. Can hold any type of data like: number, string, boolean, array, object, even another component.
How does useState work?
- useState(initialValue) is called inside a component.
- This returns an array with two elements:
- The current state value.
- A function to update that state.
Answer:
1. Lift State Up
- Put the state in the closest common parent component.
- Pass state down as props and updater functions as needed.
or
State can be shared in React by pushing state up to a parent, using the Context API, or with a state management library like Redux.
Answer: React’s event handling is very similar to DOM event handling, but with a few differences:
CamelCase naming: Instead of onclick, onClick should be used.
Pass function reference: Do not call the function directly, it is passed as a function.